The WP_Query()
only queries posts from the wp_posts
table. Even if you add additional parameters such as:
'meta_query' => array(
array(
'key' => '_thumbnail_id'
'compare' => 'EXISTS'
)
)
It looks at the wp_postmeta
table to ensure that the posts it pulls has the post_meta _thumbnail_id
but it does not also pull the post meta. The query only pulls post data from the wp_posts
table. WordPress has a ton of useful functions to get ahold of this information though:
the_post_thumbnail()
pulls and displays the post thumbnail in an<img/>
tag.get_the_post_thumbnail()
– Still pulls the post thumbnail in an<img/>
tag but does not display it. Allows you to store it into a variable for later use.
To achieve what you’re trying to do we first have to get the ID
of the post-thumbnail, then get the URL:
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'medium', true );
$thumb_url = $thumb_url_array[0];
You can switch out medium
with whatever size you need for the post thumbnail.
Alternatively, you could use get_post_meta()
to get the thumbnail ID ( or any other post meta values ):
$thumb_id = get_post_meta( $post->ID, '_thumbnail_id', true );
$thumb_url_array = wp_get_attachment_image_src( $thumb_id, 'medium', true );
$thumb_url = $thumb_url_array[0];