Question

I am setting a header image as a background image to the .blog__header block via inline styles in functions.php:

$header_image = get_header_image();

if ( $header_image ) {
    $header_image_css = "
            .blog__header {
                    background-image: url({$header_image});
            }";
    wp_add_inline_style( 'theme-styles', $header_image_css );
}

now I want to replace this header image with a featured image if set:

$header_image = get_header_image();

if ( has_post_thumbnail() ) {
    $post_thumbnail = get_the_post_thumbnail('full');
}

if ( $header_image ) {
    $header_image_css = "
            .blog__header {
                    background-image: url({$header_image});
            }";
    wp_add_inline_style( 'theme-styles', $header_image_css );
} elseif ( has_post_thumbnail() ) {
    $post_thumbnail_css = "
            .blog__header {
                    background-image: url({$post_thumbnail});
            }";
    wp_add_inline_style( 'theme-styles', $post_thumbnail_css );
}

however it doesn't work, probaly because I have not set the post ID. Any assistance would be greatly appreciated!

Was it helpful?

Solution

You did not mention or shown in the code to which hook are you hooking the above code to, but here's what I think should work. NOT TESTED

global $post;
$header_image = '';

// featured image is first priority, right?
if ( has_post_thumbnail( $post->ID ) ) {
    $header_image = get_the_post_thumbnail_url( $post->ID, 'full' );
} elseif ( !empty( get_header_image() ) ) {
    $header_image = get_header_image();
}

$header_image_css = ".blog__header { background-image: url({$header_image}); }";
wp_add_inline_style( 'theme-styles', $header_image_css );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top