Archived topic
Set featured image as site header background
3 replies · Started by Carlos on January 14, 2020
Hello,
I would like to know if it's possible set the featured image of posts as site header background.
My site header is positioned as sidebar, I use this css code for that:
@media (min-width: 769px) {
body {
margin-left: 500px;
}
.site-header {
position: fixed;
left: 0;
top: 0;
width: 500px;
z-index: 300;
height: 100%;
overflow: auto;
overflow-x: hidden;
-webkit-backface-visibility: hidden;
-webkit-overflow-scrolling: touch;
transition: .1s ease;
}
}
I've tried to do it with elements but it doesn't work, the featured image it's shown on the top instead of the sidebar.
Currently, I'm using simple css plugin to set differents images as site header background, but it would be better set them automatically.
Thank you.
Generatepress 1.9.1
Hi there,
lets give this a go. Use a Hook Element to add this to the WP_Header hook, make sure to set your display rules and check execute PHP.
<?php
// Get the featured image of current post
$featured_img_url = get_the_post_thumbnail_url(get_queried_object_id(), 'full');
// If featured image exists display as background
if ( $featured_img_url ) {
echo
'<style>
#masthead {
background-image: url("' . $featured_img_url . '");
}
</style>';
}
?>
Wow, it works perfectly!
Thank you so much, David.
Awesome - glad to be of help.