Reducing SQL queries in WordPress Templates

May 12th, 2010

If you work on a busy WordPress sites in a shared hosting environment, you know how important is to keep the number of MySQL queries down as much as possible. Even if you are using some caching plugin, it's a matter of principle.

Today I was shocked to see that one of my WordPress templates (it's based on Cutline template) is taking more than 100 queries on the index page. I was removing various parts of the template until I found that it's the the_tags() WordPress template tag.

This is the important part of the template:

<div class="entry">
<?php the_excerpt(); ?>
</div>	
<div class="postmetadata"> <p><?php the_tags( 'Tags: ', ', ', ' | ' ); ?></p> </div>

And here's a number of queries going on on my test site right now with this code:

Total Time: 78 database queries run in 0.014724969863892 seconds.

Finally I discovered that if I replace the_excerpt() with the_content() (that means the full articles are displayed, not just first few sentences), the queries go down to around 50. Is the_tags() not working with database cache and global PHP object until the whole content is shown?

I found the exact line in the_content() function which makes this happen and put it into my code, right before the_excerpt:

<div class="entry">
<?php apply_filters('the_content', ''); ?>
<?php the_excerpt(); ?>
</div>
<div class="postmetadata">
<p><?php the_tags( 'Tags: ', ', ', ' | ' ); ?></p>
</div>

Now here's the number of SQL queries: 

Total Time: 47 database queries run in 0.0041866302490234 seconds.

That means the_tags() won't take any extra queries now. Interesting! If you are developing templates, watch out for this.

The plugin I used to get the exact number of queries is WPDB Profiling.

WordPress | Comments | Trackback

del.icio.us Digg Ma.gnolia StumbleUpon Technorati Jump to the top of this page

 

2 comments on “Reducing SQL queries in WordPress Templates”

  1. 01

    Also, removing tag cloud widget (if you are using) will reduce about 20 queries.

    ivan at December 3rd, 2010 around 5:06 am
    Jump to the top of this page
  2. 02

    [...] Entre otras cosas puede ser por excesivas llamadas a la base de datos, en Foliovision te explican cómo reducir las llamadas SQL en WordPress, realmente [...]

    Zona Bloguismo XXV | Bloguismo at February 28th, 2011 around 1:25 am
    Jump to the top of this page

Leave a Reply

  •  
  •  
  •  

You can keep track of new comments to this post with the comments feed.