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