Posts Tagged ‘cache’

Speed up WordPress plugin by using postmeta

07.14.2008 by Denis - 0 Comment
Posted in WordPress

WordPress Related Posts, a plugin that I developed which has been downloaded more than 20,000 times, has an efficiency problem. I have got several times suspend in one of my blog which is hosted by bluehost because of exceeded cpu quota, and the root of the problem is SLOW SQL of the plugin.

It is true that the plugin uses a very inefficient SQL . Because the plugin finds related posts base on tag, so it needs to scan all post’s tags.By now I still haven’t got any good idea to imporve this SQL.The
second method to speed up this plugin is using cache.My method is a little different.Instead of using cache plugin, I use postmeta to cache.

As we all know that postmeta table is used to store other custom fields of post. We can store the related posts list and the save time to postmeat. Next time we only fetch related posts list from postmeat, and compare the current time and the last saved time. If it is in the allow cache time, then display. Otherwise it will fetch the related post by the slow SQL, store it to postmeta and display it.

<?php
  global $id;
 
  $output_old = get_post_meta($id, "related_posts", $single = true); // fetch related post from postmeta 
 
  if($output_old){  //if not null
    $time = time();
    if(($time - $output_old["time"])<600){  //and in allow time (600 seconds) 
      echo $output_old["related_posts"];
    }
  }else{
    $output = wp_get_related_posts() ; //fetch related post from SLOW SQL
    
    $output_new = array("time"=>time(),"related_posts"=>$output);
    
    if($output_old){//if postmeta have the record, update it 
      update_post_meta($id, 'related_posts', $output_new);
    }else{ //no, insert it
      add_post_meta($id, 'related_posts', $output_new, true);
    }
    echo $output;
  }
?>

Of course there will be a problem via this cache. The setting from configuration panel will take some time to act it.

The new version WordPress Related post: WordPress Related Posts 0.8. :-)