• Resolved wpmhweb

    (@wppit)


    Hello guys,
    I need create a post format where each post has a featured image as background, but without adding dirty styling to a div like this:
    ‘<div style=”background-image: URL (url)></div>’
    I need to do it like WordPress.com does it: https://en.blog.wordpress.com/2014/10/28/photography-101-course/

    for example:
    ‘<div class=”image”></div>’
    And on CSS should look like this:
    ‘.image {background-image: url(the url)}’

    Does anyone knows how WordPress manages to do that?
    Thanks,

Viewing 5 replies - 1 through 5 (of 5 total)
  • stephencottontail

    (@stephencottontail)

    What theme are you using? If your theme uses body_class() or post_class(), then WordPress automatically adds a number of HTML classes that can be used for styling.

    Thread Starter wpmhweb

    (@wppit)

    I’m using _underscore framework to build the theme.

    Did that already.

    But how do query the feature image for each post and add it to the background-image property without having to resource to adding insistence style inside of a div?

    I need to do it like is deployed in here: https://en.blog.wordpress.com/2014/10/28/photography-101-course/

    Thanks,

    stephencottontail

    (@stephencottontail)

    I’m not sure exactly how that blog does it, but you could write a function that would output styles to the <head>...</head> section:

    function header_post_thumbnail() {
      global $post;
    
      if ( is_single() && has_post_thumbnail() ) :
        $image_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
    
        echo '<style type="text/css">';
        echo '#masthead { background: url(' . esc_url( $image_src[0] ) . ') top left/cover; }';
        echo '</style>';
      endif;
    }
    add_action( 'wp_head', 'header_post_thumbnail', 10 );

    The #masthead would have to be large enough to contain the image or you could experiment with the various CSS background properties.

    Thread Starter wpmhweb

    (@wppit)

    Thanks,
    Adjusting my code to fit in my theme. Let you know how it works.
    Thank you for taking the time.

    Thread Starter wpmhweb

    (@wppit)

    Thanks,

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to add background-image with URL per post without dirty style to div’ is closed to new replies.