I want to get the URL of a page's "featured image", as I want to use the page's featured image as the background image for the banner at the top of the page. The background image for the banner changes according to what page I'm on, as they will have different featured images.
I want to get the URL of a page's "featured image", as I want to use the page's featured image as the background image for the banner at the top of the page. The background image for the banner changes according to what page I'm on, as they will have different featured images.
Share Improve this question edited Nov 7, 2015 at 18:35 Gabriel 2,24810 gold badges22 silver badges24 bronze badges asked Nov 7, 2015 at 16:20 King Web DevKing Web Dev 611 gold badge1 silver badge2 bronze badges3 Answers
Reset to default 5Adapted from this thread on the WP forums:
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail'); ?>
<style>
#banner-id {
background-image: url('<?php echo $image[0]; ?>');
}
</style>
<?php endif; ?>
Add this to your single page template, after the_post()
. I'd reccommend having a default header image so that if the page doesn't have a featured image it falls back to using that.
'single-post-thumbnail'
can instead be an array with the ideal header dimentions, such as array(600, 30)
.
Since you are using the image outside of the loop, you need to get the ID of the post first. Then use that to get the featured image's URL.
function wpse207895_featured_image() {
//Execute if singular
if ( is_singular() ) {
$id = get_queried_object_id ();
// Check if the post/page has featured image
if ( has_post_thumbnail( $id ) ) {
// Change thumbnail size, but I guess full is what you'll need
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'full' );
$url = $image[0];
} else {
//Set a default image if Featured Image isn't set
$url = '';
}
}
return $url;
}
Now you can use this to echo the featured image's url at header.
<?php echo wpse207895_featured_image();?>
For eaxmple:
<header class="site-header" style="background-image: url('<?php echo wpse207895_featured_image();?>');">
....
....
</header>
I found this worked for me
You can use the page's Feature Image as a background image for an element like this -->
<?php $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full' );?>
<article class="banner" style="background-image(url('<?php echo $backgroundImg[0]; ?>'))"></article>
But I would recommend using it in an image element, in the 'src' attribute -->
<article class="banner">
<?php $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full' );?>
<img src="<?php echo $backgroundImg[0]; ?>" alt="Feature Image">
</article>
and set the image size to fit whatever size the banner element is.