2

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

  • Okay thanks once again for your time and advices, much appreciated! – tslid Jun 20 '15 at 13:53
9

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

  • I also wonder if OP has $post_layout defined – birgire Jun 20 '15 at 10:36
  • Apparently he has if I read the question correctly :-) @birgire – Pieter Goosen Jun 20 '15 at 10:40
  • my thought here was that (in addition to your correction) if all posts disappeared for him, then the problem might be a wrong template path (like undefined $post_layout) or syntax error, because his syntax-wrong meta query would just results in a default query without any meta query. just wondering ;-) – birgire Jun 20 '15 at 10:45
  • If you don't pass anything to WP_Query, then you get an empty object. Remember, the arguments are only defined after doing the query :-) @birgire – Pieter Goosen Jun 20 '15 at 10:49
  • hehe you're absolutely correct, I was just babbling, too early in the morning ;-) – birgire Jun 20 '15 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.