Something like setting the div background as a style adapted from the twenty ten code, and untested code!
See if there is an image first and display the div if there is
<?php if (has_post_thumbnail( 'single-post-thumbnail' )) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" style="background-image: url('<?php echo $image; ?>')">
</div>
<?php endif; ?>
David
Thanks for the reply, but i couldn’t get this to work, the IF statement returned false even if there was a featured image to a post. Further googling led me to some code which returns the url and works beautifully:
<div class="feat" style="background-image: url('<?php
$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' =>'image') );
foreach ( $attachments as $attachment_id => $attachment ) {
echo wp_get_attachment_url( $attachment_id, 'medium' );
} ?>')">
I had a quick look and I added the wrong argument with the has_post_thumbnail, it needs the post id or nothing has_post_thumbnail( $post_id ) or has_post_thumbnail( ).
The corrected code just in case!
<?php if (has_post_thumbnail( $post->ID ) : ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" style="background-image: url('<?php echo $image; ?>')">
</div>
<?php endif; ?>
David 🙂
Fixed code. It was missing a ‘)’ in the IF and $image is an array so made the call to $image[0] for the src url.
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">
</div>
<?php endif; ?>
Thank you a lot, Styledev, I was searching this for monthes !
Brilliant.. solved my problem.. Thanks a alot styledev..
Great work… exactly what I was looking for, thank you very much.
Thanks, great code. Fits like a glove…
Should this code work with a page as well as a post? It doesnt display anything for my pages.
styledev, the code works.
However if there isn’t a featured image, how do I handle the “else” condition?
My theme has a bg image for the div. I want it to be the featured image (if one is available) and the default image if one is not available.
Good stuff, also works on wp 3.0 🙂
cheers