[wp-hackers] Reusing queries

Peter Westwood peter.westwood at ftwr.co.uk
Fri Nov 12 19:26:20 UTC 2010


On 12 Nov 2010, at 19:07, William Davis wrote:

> The site I'm working on doesn't use embedded images with posts but instead uses a few functions to see if there are images attached to the post, if those images meet a number of parameters, and finally to display those images.
> 
> So the call for an image usually looks something like this:
> if(has_image() && image_meets_params()) {
> 	image();
> }
> 
> The problem is, each of those functions queries the database, so the number of queries on a page can potentially explode.
> 
> has_image() checks to see if there are any images attached to the post at all
> image_meets_params() grabs the first image and checks the meta to see if it is a horizontal or vertical image and checks the width
> and then finally image() displays the image or images.
> 
> Is there a way to reuse some of these queries from one function to another, so for example if has_image returns true it then passes all the information onto image_meets_params? Or are these queries light enough that I need not even be worrying about it?

You should store the results in the Object Cache if you want to avoid running the queries again.

Look at the functions in wp-includes/cache.php

The default Object Cache is for the current page but there are ones to persist the contents over page views as well using Memcache, APC, XCache etc.

Cheers
-- 
Peter Westwood
http://blog.ftwr.co.uk | http://westi.wordpress.com
C53C F8FC 8796 8508 88D6 C950 54F4 5DCD A834 01C5



More information about the wp-hackers mailing list