When building templates for single posts or pages, you may wish to use the featured image of each post to display as a background. Simply adding it as a background image using the UI won’t work. Let’s look at why, and what to do instead.
Why it doesn’t work
In short, it’s because when you’re styling the template with the UI, all the styles are going into the CSS for that template. Then each post is going to use that same CSS file. So if you add in an image as a background image to that CSS, then all the posts that use that template will all have the same background image. This isn’t what we want.
In other words, you can’t use dynamic data in CSS. It needs to be in the HTML.
A solution using attributes
What we need to do is add the dynamic images into the HTML. We can do this with the ‘style’ attribute, which is just another way of adding styles to an element, but it exists inline in the HTML itself as an attribute, rather than taking it from the CSS. This way it’ll be different for each post.
Create a code snippet
We need to add a code snippet to our site, so we can have a function that returns the CSS rule that we need. I recommend the free code snippets plugin. Here’s the snippet for returning our background image rule with the featured image being fetched.
function dynamic_background_featured_img() {
return 'background-image: url(' . get_the_post_thumbnail_url() . ')';
}
Fairly simple. We can see we’re just returning the background-image CSS property and applying the ‘get_the_post_thumbnail_url’ function to it, which WP will then insert the correct image URL.
If you need a specific size, not just the full size for the background, you can add in the size as a parameter, for eg..
get_the_post_thumbnail_url('medium')
;
Create a new custom attribute
To add in Zion Builder, instead of applying a background image by going to styling > wrapper > backgrounds, we go to styling > wrapper > custom attributes. Then add a new attribute with ‘style’ as the attribute name, and our function as the value (using the “function return value” option from the dynamic settings)
The function name from the code above is ‘dynamic_background_featured_img’.
This then adds the correct image. You’ll need to then go back to the background settings to change the background positioning and background size to suit your needs.
Here’s a short recording in loom just showing the result of the wrong way to add a featured image (trying to use the featured image option and realising all the posts are using the same image) and then the right way using the attribute, giving us the correct result.