WordPress get_posts() vs query_posts() MySQL behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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