6

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.

5

Adapted 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).

| improve this answer | |
  • Happy to help. Could you mark the question as answered? Thanks. – kittsville Nov 8 '15 at 19:44
  • 1
    Should not put PHP in your CSS though – JGallardo Sep 14 '17 at 23:14
3

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>
| improve this answer | |
0

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.