Query posts only with featured image inside "pre_get_posts" hook

386 Views Asked by At

I am using the hook "pre_get_posts" to query only posts that have featured image in the front page:

add_action( 'pre_get_posts', 'my_pre_get_posts' );
function my_pre_get_posts( $q ){ 

    if (    $q->is_home()       // only target homepage
         && $q->is_main_query() // only target the main query
         && !is_admin()         // target front end only
    ) {
        $q->set( 'meta_key', array( '_thumbnail_id' ) );
    }
}

It looks like this portion is being ignored.

$q->set( 'meta_key', array( '_thumbnail_id' ) );

Your help is appreciated.

1

There are 1 best solutions below

1
On

You need to check whether '_thumbnail_id' meta_key exists or not. So let's modify your code like this.

add_action( 'pre_get_posts', 'my_pre_get_posts' );
 function my_pre_get_posts( $q ){ 
  if (    $q->is_home()       // only target homepage
     && $q->is_main_query() // only target the main query
     && !is_admin()         // target front end only
  ) {
         $meta_query = array(
             array(
                'key'=>'_thumbnail_id',
                'compare'=>'EXISTS',
             ),
         );
         $query->set('meta_query',$meta_query);
  }
 }