Get featured image url

To get the featured image URL from a WordPress post you first have to be clear which URL you should have. There are multiple sizes of the image available. The default size is “post-thumbnail”, but you can also get the “small”, “medium” and “large” sizes, or custom sizes added by add_image_size().

Use the following function to get the featured image URL by post:

$image_url = get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' );

This function uses the get_post_thumbnail_id() to retrieve the attachment id from the post meta field “_thumbnail_id” and inserts this id into the wp_get_attachment_image_src() function as follows:

// Retrieve attachment id from post meta 
$attachment_id = get_post_thumbnail_id( $post_id ); 

// Inserts attachment id to retrieve attachment url
wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false );

To extract the attachment id from the post’s post meta use the following meta key:

$attachment_id = get_post_meta( $post_id, '_thumbnail_id', true );

Notice that you should have post thumbnails enabled before you can use featured images in WordPress.

add_theme_support( 'post-thumbnails' ); 
Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals