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(); ?>
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):
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:
The following Html CSS will show image in mobile view only
Html:
Css: