The big issue you have here is calling your post thumbnails. That adds about two queries per post, which is quite heavy. When we look at the source code of get_the_post_thumbnail()
, we will see that the thumbnails is only cached on the main query, and not custom queries. So we would need to do that manually.
You can add
update_post_thumbnail_cache( $footer_query );
just before your loop. This should take care of the large amount of db calls
Just a few notes on your code
-
You should be using
wp_reset_postdata()
after the loop, notwp_reset_query()
, latter is used in conjuction withquery_posts
which you should never use.wp_reset_postdata()
should also be called betweenendwhile
andendif
-
Random ordering is always much slower than any other ordering as it still goes through the complete db in order to pick random posts, so you might want to look into this
-
It is unnecessary defining arguments with their default values.
post_type
by default is set topost
andpost_status
topublish
-
Properly indent your code to make it more readable, maintainable and debuggable
-
As from PHP 5.4, you can use short array syntax which requires less writing 😉
You can probably rewrite your code as follow
$args = [
'posts_per_page' => 18,
'orderby' => 'rand',
'no_found_rows' => true, // counts posts, remove if pagination require
// look for post which has featured img
'meta_query' => [
[
'key' => '_thumbnail_id',
]
]
];
$footer_query = new WP_Query( $args );
// Update the thumbnail cache
update_post_thumbnail_cache( $footer_query );
// LOOP
if ($footer_query->have_posts()) :
while ($footer_query->have_posts()) :
$footer_query->the_post();
?>
<a href="https://wordpress.stackexchange.com/questions/217998/<?php the_permalink() ?>">
<?php echo get_the_post_thumbnail( get_the_ID(), 'small_thumbnail', array('class' => 'img-responsive') ); ?>
</a>
<a href="https://wordpress.stackexchange.com/questions/217998/<?php the_permalink() ?>">
<?php the_title(); ?>
</a>
<?php
endwhile;
wp_reset_postdata();
endif;