How to find WordPress posts that have a featured image

One of the things I love about developing with WordPress is that you very rarely have to reinvent the wheel. Somewhere, if you can find it, is a function that does what you want.

I needed a list of post IDs that had featured images. I COULD have retrieved a complete published posts list and checked each one to see if it had a post thumbnail, but there is a much more efficient way – a new WP_Query. Set the arguments and let WP do the work for you.

Here’s the function that returns the list:

	function mgf_get_sponsor_list() {
		$args = array(	'posts_per_page'	=> -1,
						'post_type'			=> 'post',
						'meta_key'			=> '_thumbnail_id',
						'post_status'		=> 'publish',
						'fields'			=> 'ids'
		$sp = new WP_Query( $args );
		return ( ! empty( $sp->posts ) ) ? $sp->posts : false;

The $args are the key to getting what you want. I needed only posts with attached thumbnails, and I didn’t need all of the post details, just the ID. $args[‘fields’] = ‘ids’ takes care of returning only IDs, and $args[‘meta_key’] chooses only those posts with featured images.

In the above, $sp returns the whole WP_Query object, but I only needed the posts part, so the function returns only ->posts.

That’s all there is to it.

You can use the above in a theme functions file or in a plugin.

See the Class Reference/WP Query « WordPress Codex for more information on using the WP_Query class.