329 posts
  • Has been part of the Envato Community for over 4 years
  • Has referred 10+ members
  • Has sold $40,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
PaulWinslow says

Afternoon,

I’m trying to get the post thumbnail / featured image from a custom post-type to use it as the background image of each post in my loop..

I found this: http://wpengineer.com/2123/use-wordpress-post-thumbnail-as-background-image/

But it doesn’t work.

The fallback image is used just fine, but if you set a featured image to the post it doesn’t work, it doesn’t get the image URL at all, so I end up with..

.project-scroll { background: url(’ ‘) 50% 0 no-repeat fixed; }

At the moment I don’t see how the code in the tutorial is supposed to actually work, because I can’t see how it’s supposed to check if there’s an image set when my loop is in a custom page template elsewhere..

Has anybody managed to do this? Any help would be brilliant.

No inline styles.

Cheers,
Paul

1476 posts
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Made it to the Authors' Hall of Fame
+3 more
OriginalEXE says

Hi Paul,

here is an example function:

if ( ! function_exists( 'prefix_post_background' ) ) {

    function prefix_post_background( $post_id = null, $echo = true ) {

        if ( ! $post_id ) $post_id = get_the_ID(); // id not passed, get current post in a loop

        if ( ! $post_id ) return; // could not get post id, and it was not passed in a function

        $thumb_id = get_post_thumbnail_id( $post_id );

        if ( ! $thumb_id ) return; // no featured image set

        $img_src = wp_get_attachment_image_src( $thumb_id, 'full', true );

        $custom_css = 
            "<style type='text/css'>
                #post-$post_id {
                    background-image: url( '$img_src[0]' );
                }
            </style>";

        if ( ! $echo ) return $custom_css;

        echo $custom_css;

    }

}

You would place it in your custom loop code (function call I mean).

329 posts
  • Has been part of the Envato Community for over 4 years
  • Has referred 10+ members
  • Has sold $40,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
PaulWinslow says

Am I supposed to replace some of these variables with something else? $post_id etc?

329 posts
  • Has been part of the Envato Community for over 4 years
  • Has referred 10+ members
  • Has sold $40,000+ on Envato Market
  • Has collected 100+ items on Envato Market
+2 more
PaulWinslow says

Ahhh that’s perfect. I could kiss you!

1476 posts
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Made it to the Authors' Hall of Fame
+3 more
OriginalEXE says

You are welcome :)

by
by
by
by
by
by