jasondevine
3/6/2017 - 3:09 PM

WordPress Responsive Background Images

WordPress Responsive Background Images

/**
 * Responsive Featured Image Background - used to set custom responsive background on each page.  I should probably turn this into a plugin at some point.
 * Based on the work by Steven Slack: @link http://s2webpress.com//responsive-featured-image-function-in-wordpress-themes/
 *
 */
 
 function my_featured_image() {
    // call the global post variable
    global $post;
 
    // If the page/post has a featured image
    if (has_post_thumbnail()) :
         
        // get the post thumbnail ID for the page or post
        $post_thumbnail_id = get_post_thumbnail_id( $post->ID );
         
        // store the image sizes in an array.  I only did medium and up as the WP default thumbnail size is very small
        $img_sizes = array( 'medium', 'large', 'full' );
     
        // grab the URL for each image size and store in a variable
        foreach ( $img_sizes as $img_size ) {
            ${ 'img_src_' . $img_size } = wp_get_attachment_image_src( $post_thumbnail_id, $img_size );
        }
     
        // Set the media queries to whatever width works for your design
        echo '<style type="text/css"> 
            .bg-image {
                background-image: url(' . esc_url( $img_src_medium[0] ) . '); 
                background-size: cover;
                background-repeat: no-repeat;
                background-position: top center;
                background-attachment: fixed;
            }
     
            @media screen and ( min-width: 400px ) {
                .bg-image {
                    background-image: url(' . esc_url( $img_src_large[0] ) . ');
                }
            }
     
            @media screen and ( min-width: 1000px ) {
                .bg-image {
                    background-image: url(' . esc_url( $img_src_full[0] ) . ');
                }               
            }
        </style>';
    endif;
    
} // end function my_featured_image
 
add_action( 'wp_head', 'my_featured_image' );