Using featured img as div background

Try something like this:

<?php
global $post;

$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
$default = get_template_directory_uri()."/assets/images/backgrounds/highway.jpg";
$bgimg = (isset($src[1])) ? $src[0] : $default;
?>

<style type="text/css">
.parallax { background-image: url(<?= $bgimg ?>); }
</style>

wp_get_attachment_image_src() says it returns false when not found, but for some reason I’ve had bad time with that, so I just check if the width of a found image is returned ($src[1]) instead. Always works.

get_template_directory_uri() is a better approach than a relative path – you’ll find that as this starts showing on other pages than the homepage. Depending on your site, this might of actually been what your issue was.


Here’s a slightly better way to write it, with one less query, for efficiency

<?php
global $post;

$img = get_template_directory_uri()."/assets/images/backgrounds/highway.jpg";

$postThumb = get_post_thumbnail_id($post->ID);
if (!empty($postThumb)) {
    $src = wp_get_attachment_image_src( $postThumb, array( 5600,1000 ), false, '' );
    if (isset($src[1]))
        $img = $src[0];
}

?>

<style type="text/css">
.parallax { background-image: url(<?= $img; ?>); }
</style>

PS here’s how to format code on this site.

UPDATE:

$post won’t always be the current PAGE your on, if your on an ARCHIVE, your main feed, and so on, as you’ve found when listing posts its the first post. So you may need to conditionals what the current page actually is:

<?php
global $post;

$thisPage = false;

if (is_singular())
    $thisPage = $post;
elseif (is_home())
    $thisPage = get_post(get_option('page_for_posts'));
// other conditionals for other non-singular things here


if ($thisPage) {
    $postThumb = get_post_thumbnail_id($thisPage->ID);  
    // etc