I’m adding a featured image on my page through the dashboard and I want to use it as a background image on the container div of the page.
I want to apply the background image through css, so I am thinking to put a style attribute inside my markup.
I’m thinking to make something like this:

<div id="<?php echo $post_name; ?>" class="page<?php echo $post_id; ?>" style="background: url(<?php wp_get_attachment_image_src( get_post_thumbnail_id(), 'large' ); ?>) !important;">

But unfortunately this is not working.

When I check the output is like this:

background: url() !important;

What is wrong with this ?
Any suggestions?
Thanks!

2 s
2

You need to echo the return value from wp_get_attachment_image_src(). It also returns an Array(), so you need to grab the needed part from that array. In this case it’s the first/0 value. Example:

<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div id="post" class="your-class" style="background-image: url('<?php echo $thumb['0'];?>')">
<p>your text demo</p>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *