I’m having hard times with showing only posts which have featured images using the loop. My PHP level is basic and any help will be really useful.

So basically this is my original code :

if( have_posts() ) { 
    while( have_posts() ) { 
        the_post();
        get_template_part( 'inc/template-parts/content', $post_layout );
        // and some other stuff
    }
}

I tried the advice from this thread – How do I check if a post has a post thumbnail in WP_Query?
But without any success. When I implement the code all posts disappear from the front page.

This is the code I tried:

$query = new WP_Query( $thumbs );
$thumbs = array(
    'meta_query' => array( 'key' => '_thumbnail_id' ) 
);
if( $query->have_posts() ) { 
    while( $query->have_posts() ) { 
        $query->the_post();
        get_template_part( 'inc/template-parts/content', $post_layout );
    } 
} 

Any advice will be appreciated!
Regards

2 Answers
2

You need to define your arguments before you pass them to WP_Query, not after. Also, your meta_query should be an array of an array, not just an array

This

 $query = new WP_Query($thumbs);
 $thumbs = array(
        'meta_query' => array('key' => '_thumbnail_id') 
 );

should look like this

 $thumbs = array(
    'meta_query' => array( 
        array(
            'key' => '_thumbnail_id'
        ) 
    )
 );

 $query = new WP_Query($thumbs);

EDIT

Just a few extra notes

  • Make sure to reset postdata after a custom query. Just add wp_reset_postdata(); before you close your if statement and just after closing your while statement

  • I believe that a custom query might not be necessary here. If I read your question correctly, you can simply use pre_get_posts to alter the main query. You shouldn’t use a custom query just because you want to alter the main query

Leave a Reply

Your email address will not be published. Required fields are marked *