Last active
October 11, 2017 19:00
-
-
Save wking-io/210693d2403ebb7ab44c9fcdc864bd48 to your computer and use it in GitHub Desktop.
Add responsive background images for slider and preload them. #library #wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// make sure it is the correct template | |
if (is_page_template( 'templates/template.php' )) : | |
$slider_posts = array(); | |
// check if the repeater field has rows of data | |
if( have_rows('slider_posts') ) : | |
// loop through the rows of data | |
while ( have_rows('slider_posts') ) : the_row(); | |
// display a sub field value | |
if (!empty(get_sub_field('the_post'))) : | |
$the_post = get_sub_field('the_post'); | |
endif; | |
$slider_posts[] = $the_post->ID; | |
endwhile; | |
endif; | |
// make sure images were returned | |
if (!empty($slider_images)) : | |
// foreach post in the slider | |
foreach($slider_images as $id) : | |
// get the image field from that post | |
$img = get_field('the_img', $id); | |
ob_start(); ?> | |
<link rel="preload" href="<?php echo $img['url']; ?>" as="image media="(min-width: 1440px)"> | |
<link rel="preload" href="' . $img['sizes']['l-xl'] . '" as="image media="(max-width: 1440px)"> | |
<link rel="preload" href="' . $img['sizes']['l-l'] . '" as="image media="(max-width: 966px)"> | |
<style> | |
.slider__item[data-id="<?php echo $img['id']; ?>"] { | |
background-image: url(<?php echo $img['sizes']['xl']; ?>); | |
} | |
@media screen and (min-width: 1440px) { | |
.slider__item[data-id="<?php echo $img['id']; ?>"] { | |
background-image: url(<?php echo $img['url']; ?>); | |
} | |
} | |
@media screen and (max-width: 966px) { | |
.slider__item[data-id="<?php echo $img['id']; ?>"] { | |
background-image: url(<?php echo $img['sizes']['l']; ?>); | |
} | |
} | |
</style>'; | |
<?php ob_end_flush(); | |
endforeach; | |
endif; | |
endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment