10

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
  • Have you already searched the site?
    – kaiser
    Commented Sep 27, 2013 at 16:53
  • Yes I did a research but it seems to not work proper, I've updated my question, check now please!
    – agis
    Commented Sep 27, 2013 at 17:07

2 Answers 2

14

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>
5
  • Please explain why this should help the OP. Thanks.
    – kaiser
    Commented Sep 27, 2013 at 17:14
  • @kaiser was also working with backgrounds that way, I am newbie, do not know why, but I know it worked for what I saw in a forum.
    – Raank
    Commented Sep 27, 2013 at 17:22
  • @Feera Well, then it's Magic. And know that Magic always is the answer :D
    – kaiser
    Commented Sep 27, 2013 at 17:28
  • may be little, but what matters is the intention :P
    – Raank
    Commented Sep 27, 2013 at 17:31
  • 2
    If you're doing this in a function, don't forget to precede this code with global $post; . Commented Jan 15, 2016 at 20:15
2

Try to use the the_post_thumbnail_url function:

Gets the direct image URL for the featured image of the current post.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.