Get featured image url

To get the featured image url from a post you first have to be clear which url you should have. There are multiple formats 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' ); 

Leave a reply

Feel free to ask questions or make comments.

Comments

    No comments yet..