322 posts
  • Bought between 100 and 499 items
  • Exclusive Author
  • Has been a member for 4-5 years
  • Referred between 10 and 49 users
  • Sold between 50 000 and 100 000 dollars
  • United Kingdom
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

1400 posts
  • Has been a member for 2-3 years
  • Exclusive Author
  • Sold between 10 000 and 50 000 dollars
  • Bought between 10 and 49 items
  • Referred between 1 and 9 users
  • Croatia
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).

322 posts
  • Bought between 100 and 499 items
  • Exclusive Author
  • Has been a member for 4-5 years
  • Referred between 10 and 49 users
  • Sold between 50 000 and 100 000 dollars
  • United Kingdom
PaulWinslow says

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

322 posts
  • Bought between 100 and 499 items
  • Exclusive Author
  • Has been a member for 4-5 years
  • Referred between 10 and 49 users
  • Sold between 50 000 and 100 000 dollars
  • United Kingdom
PaulWinslow says

Ahhh that’s perfect. I could kiss you!

1400 posts
  • Has been a member for 2-3 years
  • Exclusive Author
  • Sold between 10 000 and 50 000 dollars
  • Bought between 10 and 49 items
  • Referred between 1 and 9 users
  • Croatia
OriginalEXE says

You are welcome :)

by
by
by
by
by
by