Featured image in WordPress posts is a great feature and in earlier versions of WordPress, adding thumbnails was a pain but no more.. But getting only posts with thumbnails is still not that straight forward.
With WP_Query, you need to use ‘meta_query’ in your query with comparison operator to get to correct results, all other ways of using meta_key with the args did not work.
I have written the following function that you can place in your functions.php file and call it anywhere in your theme. I have also added pagination support and if you want to get posts only from a specific user, provide his user_id.
This function also supports pagination, just provide the number of required posts per page and page number and you will get required result.
Here is the function code, place this in your functions.php file:
function get_posts_with_thumb($posts_per_page=10, $page=1, $user_id='' ){
$offset = ($page * $posts_per_page) - $posts_per_page;
$args = array( 'author'=>$user_id,
'posts_per_page' => $posts_per_page,
'offset' => $offset,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'value' => '',
'compare' => '!=',
)
)
);
$posts_with_photos = new WP_Query( $args );
foreach($posts_with_photos->posts as $p){
$aTemp = new stdClass();
$thumb_id = (int)get_post_thumbnail_id($p->ID);
$aTemp->post_id = $p->ID;
$aTemp->author = $p->post_author;
$aTemp->post_date = $p->post_date;
$aTemp->title = $p->post_title;
$aTemp->comment_count = $p->comment_count;
$aTemp->image = wp_get_attachment_image_src( $thumb_id, 'thumbnail');
$aTemp->photo = wp_get_attachment_image_src( $thumb_id, 'full');
$aTemp->content = $p->post_content;
$oReturn->posts[] = $aTemp;
}
return $oReturn;
}
This is how you need to call in your WordPress theme files:
$posts = get_posts_with_thumb();
// or with args
$posts = get_posts_with_thumb($posts_per_page=10, $page=1, $user_id=28);
print_r($posts);
Hope that helps!