Inline HTML background-image using PHP logic?

Is it possible to use my PHP logic used to display a WordPress post’s featured image as the inline background image of a div? Here is my attempt:

                <div class="rounding-image" style="background-image: url(
                    <?php
                        if ( $thumbnail == true ) {
                            // If the post has a feature image, show it
                            if ( has_post_thumbnail() ) {
                                the_post_thumbnail( $thumbsize );
                            // Else if the post has a mime type that starts with "image/" then show the image directly.
                            } elseif ( 'image/' == substr( $post->post_mime_type, 0, 6 ) ) {
                                echo wp_get_attachment_image( $post->ID, $thumbsize );
                            }
                        }
                    ?>
                )"></div>

This isn’t throwing a specific error, but rather displaying )"> where the image would be.

Related posts

Leave a Reply

3 comments

  1. the_post_thumbnail displays the image with the img tag. What you want to do is get the image URL

    $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); $url = $thumb['0'];
    
    if ( has_post_thumbnail() ) {echo $url;}
    
  2. I like to use background-size: cover if its full width. if it’s not just remove that part of the css

    <?php if (has_post_thumbnail( $page->ID ) ) { ?>
          <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), 'single-post-thumbnail' ); ?>
    
    <header style="background:url(<?php echo $image[0]; ?>) 50%  50% no-repeat;background-size: cover;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cover;"></header>
    
    <?php } ?>
    
  3. Use this, it will set the background image to the featured image if one exists. This allows you to set a default via CSS in case a featured image is not set.

    <?php 
        global $post; 
        $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' ); 
        if ( has_post_thumbnail() ) :
    ?>
    
        <div class="rounding-image" style="background: url(<?php echo $src[0]; ?> ) !important;">
    <?php else : ?>
        <div id="rounding-image">