I want to hide posts without images on the front page, so I need get an array of ids of those posts.

I know how hide posts on the home page by id, but I need to show only posts with images. This is what I have already:

function exclude_post($query) {

  if ($query->is_home)  {
      $query->set('post__not_in', array(1,2) );
    return $query; 
  • 1
    You mean you want only posts with thumbnails? – Rene Korss May 9 '15 at 12:11

No need for post IDs what has no thumbnail. Use meta query to get only those what has thumbnail.

Add meta query

function get_only_posts_with_images( $query ) {

  if ( $query->is_home() && $query->is_main_query() )  {
      $query->set( 'meta_query', array( array( 'key' => '_thumbnail_id' ) ) );

add_action( 'pre_get_posts', 'get_only_posts_with_images' );

Or use custom query.

$query = "
  SELECT posts.* 
  FROM $wpdb->posts AS posts
  INNER JOIN $wpdb->posts AS attachment 
    ON attachment.`post_parent`=posts.`ID` 
      AND attachment.`post_type`='attachment' 
  WHERE posts.`post_type`='post'

$posts_with_images = $wpdb->get_results( $query, OBJECT );
  • thanks i used meta query, but after if i open single post, image is not shown. In front page ok, but if open any post, image doesn't show. I am new in wordpress, maybe its because array( 'key' => '_thumbnail_id' ) ? – Tolik May 10 '15 at 11:43
  • No, it's not because of that. Try to see if your template even shows thumbnails on single post and debug it a little. – Rene Korss May 11 '15 at 8:15
  • 1
    Great approach ( with pre_get_posts ). I have altered your code to include the main query check otherwise all custom queries on the home page will be altered too – Pieter Goosen May 11 '15 at 8:19
  • See this post on how to use pre_get_posts correctly :-) – Pieter Goosen May 11 '15 at 8:22
  • 1
    That is great answer and explanation. Edited my code accordingly. – Rene Korss May 11 '15 at 8:27

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.