Skip to content

Instantly share code, notes, and snippets.

@zachstronaut
Created October 6, 2012 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zachstronaut/3843393 to your computer and use it in GitHub Desktop.
Save zachstronaut/3843393 to your computer and use it in GitHub Desktop.
WordPress get_posts() vs query_posts() MySQL behavior
<?php
/**
* Am I missing something obvious? Is there some flag for caching attachments or something?
*
* My actual use case is pulling all the posts from a custom post type... but the behavior is the same with good old plain posts, too.
* Your test posts will need Featured Images.
*/
/**
* Use one or the other PHP block in this gist... not both.
* Place this in any theme template file between the get_header/get_footer
*/
$args = array(
'post_type' => array('post'),
'post_per_page' => -1,
'posts_per_archive_page' => -1,
'nopaging' => true
);
query_posts($args);
while (have_posts()) : the_post();
// Number of MySQL queries is fixed, regardless of number of posts
// (Measured with Debug Objects plugin)
?>
<p><?php the_post_thumbnail(); ?></p>
<?php
endwhile;
wp_reset_query();
?>
<?php
/**
* Use one or the other PHP block in this gist... not both.
* Place this in any theme template file between the get_header/get_footer
*/
$args = array(
'post_type' => 'post',
'post_per_page' => -1,
'posts_per_archive_page' => -1,
'nopaging' => true
);
$posts = get_posts($args);
// Can do it this way too with same behavior
//$query = new WP_Query($args);
//$posts = $query->posts;
foreach ($posts as $post) {
// get_the_post_thumbnail() here results in 3 MySQL queries PER POST!!
// (Measured with Debug Objects plugin)
?>
<p><?= get_the_post_thumbnail($post->ID); ?></p>
<?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment