Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Gabriel Ward
Gabriel Ward
20,222 Points

WordPress and background images.

I'm wanting to create a page template that has a hero picture at the top of the page like this page

http://madebyfieldwork.com/us/

For this page, the image is being positioned using background-image property in CSS. If I was to insert a feature image into the page, would it be possible to set the feature image as the value for the page's background-image property? I'm guessing I'd need to use php to get the feature image, but not sure how I might use php in CSS. Is it possible?

Thanks for any help/advice, I greatly appreciate it.

1 Answer

You can't use php in a .css file, but you can set css properties with php using inline css, something like this:

First add this function to your functions.php

function get_page_feat_image_src() {
    global $post;
    $page_id = $post->ID;
    if (has_post_thumbnail( $page_id )){
        $post_thumbnail_id = get_post_thumbnail_id( $page_id );
        $page_feat_image = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );
        return $page_feat_image[0];
    } 
    return false;
}

Then in the pages you want your background image add this markup:

<div class="hero-img-wrapper" style="background-image: url(<?php echo get_page_feat_image_src(); ?>)">
</div>

Then add the rest of the styles for that div in your css:

.hero-img-wrapper {
   background-size: cover;
   background-position: center;
}

Let me know how you go.

Gabriel Ward
Gabriel Ward
20,222 Points

Thank you Sergio I will most certainly let you know how I get on.

Cheers,

Gabe

Gabriel Ward
Gabriel Ward
20,222 Points

Hi Sergio,

I'm just wondering, I'd need to add a filter to the code in the functions.php right? Only, thing is I'm not entirely sure of what goes in the first parameter of the filters code. Do you have any suggestions?

<?php

function get_page_feat_image_src() {
    global $post;
    $page_id = $post->ID;
    if (has_post_thumbnail( $page_id )){
        $post_thumbnail_id = get_post_thumbnail_id( $page_id );
        $page_feat_image = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );
        return $page_feat_image[0];
    } 
    return false;
}

add_filter('//don't know what goes here', 'get_page_feat_image_src()');

?>

Thanks,

Gabe