Skip to content

Instantly share code, notes, and snippets.

@zephyrmike
Created August 16, 2023 22:55
Show Gist options
  • Save zephyrmike/ac6d114b148b15ce612bad260890cdd2 to your computer and use it in GitHub Desktop.
Save zephyrmike/ac6d114b148b15ce612bad260890cdd2 to your computer and use it in GitHub Desktop.
Responsive Hero Background Images That Randomly Change
<?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