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' );
// 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' );