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!
if the result you’re looking for is a printout of the URL, like in your example, then this should work:
You have a couple of syntax errors, but in your question you state that…
wp_get_attachment_url
takes the actual attachment ID, not the page ID to which the featured image is attached. I therefore assume that the question is “Why am I not getting the image URL that I expect?”What you need is to use
get_post_thumbnail_id
and pass that towp_get_attacment_url
…… possibly with a second argument to specify size.
I hope I guessed correctly 🙂
Little late here, but I created a solution that is a bit cleaner and reusable with some of the suggestions in this thread. Add this anywhere in your functions.php file, then simply call this function wherever you need it. You can supply the post id if you have it, if not it’s not required.
This got it working and got me the image URL:
Thanks for all your help, it put me in the right direction.
Add theme support for thumbnail
add_theme_support('post-thumbnails');
Then write the below code on your archive page. It works before your WordPress loop