Dynamically change background image in the CSS during WordPress loop (media queries)

I currently have a carousel on my page inside a WordPress loop. So as it loops through it changes the background image according to which post I am currently on in the loop. However, I want to use media queries to load smaller images if for instance I the screen size is smaller.

This is what I currently have:

    while( $loop->have_posts() ) : $loop->the_post();


        $class = '';

        // Custom Posts
        $carousel_image_1       = get_field('carousel_image_1');
        $image_1_title          = get_field('image_1_title');

        if( $slide_counter == 0 ) { $class .= ' active'; }

?>

        <div class="item <?php echo $class ?> <?php echo "slide_" . $slide_counter ?>">
            <!-- Set the first background image using inline CSS below. -->
            <a href="<?php echo get_post_permalink(); ?>" target="_blank">
            <div class="fill" style="background-image:url(<?php echo $carousel_image_1['url']; ?>); background-size:cover;" alt="<?php echo $carousel_image_1['alt']; ?>"> </div>
            <div class="carousel-caption">
                <h2><?php echo $image_1_title; ?></h2>
                <img width="80" class="book" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/book.png" alt="">
            </div>
            </a>
        </div>

        <?php $slide_counter++; ?>

    <?php endwhile; wp_reset_query(); ?>

Related posts

2 comments

  1. You can’t use media queries inline, and you won’t be able to have the dynamic flexibility of your variables in CSS, because PHP is server-side.

    But, you could do this with JavaScript as long as the JS is able to get the PHP variables (my example uses jQuery):

    <?php
    while( $loop->have_posts() ) : $loop->the_post();
    
        $class = '';
    
        // Custom Posts
        $carousel_image_1       = get_field('carousel_image_1');
        $carousel_image_2       = get_field('carousel_image_2'); // added this, for different size image
        $image_1_title          = get_field('image_1_title');
    
        if( $slide_counter == 0 ) { $class .= ' active'; }
    
    ?>
    
        <div class="item <?php echo $class ?> <?php echo "slide_" . $slide_counter ?>">
            <a href="<?php echo get_post_permalink(); ?>" target="_blank">
            <div class="fill" style="background-size:cover;" alt="<?php echo $carousel_image_1['alt']; ?>"> </div>
            <div class="carousel-caption">
                <h2><?php echo $image_1_title; ?></h2>
                <img width="80" class="book" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/book.png" alt="">
            </div>
            </a>
        </div>
    
        <script>
        var resizeTimer;
        function resizer() {
          clearTimeout(resizeTimer);
          resizeTimer = setTimeout(function() {
            var windowWidth = $(window).width();
            if (windowWidth >= 992) { // for width 992 pixels and up
              $('.fill').css({
                'background-image': 'url(<?php echo $carousel_image_1["url"]; ?>)';
              });
            } else { // smaller sizes
              $('.fill').css({
                'background-image': 'url(<?php echo $carousel_image_2["url"]; ?>)';
              });
            }
          }, 200);
        }
        resizer();
        $(window).on('resize', resizer);
        </script>
    
        <?php $slide_counter++; ?>
    
    <?php endwhile; wp_reset_query(); ?>
    

    I haven’t tested it but I think it should work. You can also adjust the timeout to your preference (right now it’s 200ms).

    Or if you wanted to not make it truly responsive, and just set the background on page load, you could just write:

    <script>
    if (windowWidth >= 992) { // for medium size width and up
      $('.fill').css({
        'background-image': 'url(<?php echo $carousel_image_1["url"]; ?>)';
      });
    } else { // smaller sizes
      $('.fill').css({
        'background-image': 'url(<?php echo $carousel_image_2["url"]; ?>)';
      });
    }
    </script>
    
  2. The following Html CSS will show image in mobile view only

    Html:

     foreach($data as $item):
         echo "
         <div class='col-lg-4'> 
                            <div class='panel panel-primary backImg' style='background-image:url({$item['imageLink']}); background-size:100% 100%;'>   
                     Some Text
            </div>
         </div>";
       endforeach;
    

    Css:

    @media(min-width: 480px){ 
        .backImg{
            background-image:none !important;
        }
    }
    

Comments are closed.