How to user WP_Query to lower the number of queries

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, not wp_reset_query(), latter is used in conjuction with query_posts which you should never use. wp_reset_postdata() should also be called between endwhile and endif

  • 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 to post and post_status to publish

  • 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;

Leave a Comment

error code: 523