Created
August 16, 2023 22:55
-
-
Save zephyrmike/ac6d114b148b15ce612bad260890cdd2 to your computer and use it in GitHub Desktop.
Responsive Hero Background Images That Randomly Change
This file contains hidden or 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 | |
// random choice of image from ID array | |
$att_id = array(#, #, #, #, #, #); | |
$rnd_att_id = $att_id[array_rand($att_id)]; | |
$full_img_url = wp_get_attachment_image_src($rnd_att_id, 'full'); | |
$md_lg_img_url = wp_get_attachment_image_src($rnd_att_id, 'medium_large'); | |
// preload our random image if the exist | |
if ( !empty( $full_img_url ) && !empty( $md_lg_img_url ) ) { | |
echo '<link rel="preload" as="image" href="' . esc_url($full_img_url[0]) . '" type="image/jpeg" media="(min-width: 768px)">'; | |
echo '<link rel="preload" as="image" href="' . esc_url($md_lg_img_url[0]) . '" type="image/jpeg" media="(max-width: 767px)">'; | |
// Output the responsive CSS for setting the background image | |
?> | |
<style> | |
.random-background { | |
background-size: cover; | |
background-position: center; | |
background-repeat: no-repeat; | |
} | |
@media (min-width: 768px) { | |
.random-background { | |
background-image: url('<?php echo esc_url($full_img_url[0]); ?>') !important; | |
} | |
} | |
@media (max-width: 767px) { | |
.random-background { | |
background-image: url('<?php echo esc_url($md_lg_img_url[0]); ?>') !important; | |
} | |
} | |
</style> | |
<?php | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment