Wordpress: Cache your $wpdb queries


/ Published in: PHP
Save to your folder(s)

Cache the results of your wordpress database queries for faster page generation


Copy this code and paste it in your HTML
  1. /**
  2. * Usage: Rename the function and add your own $sql
  3. */
  4.  
  5. function test_function(){
  6. global $wpdb;
  7.  
  8. //check if there is some past cached results
  9. $result = wp_cache_get(date('Y-m-d'), __FUNCTION__);
  10.  
  11. //if there wasn't a cached result, run your query
  12. if($result === false)
  13. {
  14. //place your SQL here
  15. $sql = "SELECT p.post_author
  16. FROM $wpdb->posts p
  17. WHERE p.post_status = 'publish'
  18. AND p.post_type = 'business' ";
  19.  
  20. $result = $wpdb->get_col($sql);
  21.  
  22. //once the query has been run, cache the results
  23. wp_cache_add(date('Y-m-d'), $result, __FUNCTION__);
  24. }
  25. return $result;
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.