I need to get the featured image outside the loop. This is so that I can have a different full-screen background image for each page, set by the featured image.

After doing some research I was able to get the post ID outside the loop.

This is what I’ve got:

$page_object = get_queried_object();
$page_id     = get_queried_object_id();
$bkgdImg = wp_get_attachment_url( $page_id );
if (!empty($bkgdImg)) {
    $backgroundImg = $bkgdImg;
}
else {
    $defaultbackground = . get_template_directory_uri() . "/images/default-background.jpg";
    $backgroundImg = $defaultBackground;
}

echo $backgroundImg;

Thanks!

5 Answers
5

if the result you’re looking for is a printout of the URL, like in your example, then this should work:

$page_id = get_queried_object_id();
if ( has_post_thumbnail( $page_id ) ) :
    $image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $page_id ), 'optional-size' );
    $image = $image_array[0];
else :
    $image = get_template_directory_uri() . '/images/default-background.jpg';
endif;
echo $image;

Leave a Reply

Your email address will not be published. Required fields are marked *