0

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!

2

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 );
  • Thanks, Junaid! I am using the following hook: add_action( 'wp_enqueue_scripts', 'touche_inline_styles' );. I will test your code and get back to you. Thanks again! – Deka87 Jul 7 '17 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.