Adding CSS that contains pHp

I have this piece of code which inserts a featured image into the header of a page/post similar to the blog layout.

if (has_post_thumbnail()) { //if a thumbnail has been set
	$imgID = get_post_thumbnail_id($post->ID); //get the id of the featured image
	$featuredImage = wp_get_attachment_image_src($imgID, 'full' );//get the url of the featured image (returns an array)
	$imgURL = $featuredImage[0]; //get the url of the image out of the array
	.header-image {
		background-image:url('<?php echo $imgURL ?>');
		background-size: cover;
		width: 100%;
		height: 450px;
}//end if

The only file I can think to place this code into (and where it works) is head.php, but I would rather not have styles in the head tags. Is there an appropriate way to insert CSS that contains pHp? Thanks in advance.

I’m doing something similar on a site I’m building now.

Put all of the .header-image CSS into your app.less file. Then, output the html with a single inline style:

<header class="header-image" style="background-image:url('<?php echo $imgURL ?>');"></header>

By the way, have you actually looked at the source of medium’s header images? They control stuff like shading and gradient overlays via URL params. Very very cool.

1 Like

Thanks willthemoor! Yes, Medium’s site is super cool and doing it right and light.

Hi all,

Did anyone succeed doing this in Sage? Could you please share how you did this?


@svdb The above should still work just fine. What exactly are you trying to do? What have you tried?

Hi @willthemoor,

Thank you for getting back to me. The following works for me in my template file:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); 
        if ( has_post_thumbnail() ) {
            $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() );
            echo '<section class="image-featured" style="background-image:url('.$feat_image_url.');"></section>';