Hello, I've seen this done before, can anyone help me with the code?
Based on my server time or site time I would like show a different background image at different times of the day.
6am-10am - sunrise.jpg
10am-5pm - day.jpg
5pm-7pm- sunset.jpg
7pm-6am- night.jpg
Can this be done for a background image? Using body class.
Thank you
Arnav Joy answers:
write following to functions.php
add_filter('body_class','my_body_classes');
function my_body_classes($classes, $class) {
// add 'my-class' to the $classes array
$classes[] = 'my-class';
// return the $classes array
return $classes;
}
write following before closing head tag in header.php
<?php
$time = date("H");
if( $time >= 06 && $time < 10 )
$img_name = 'sunrise.jpg';
if( $time >= 10 && $time < 17 )
$img_name = 'day.jpg';
if( $time >= 17 && $time < 19 )
$img_name = 'sunset.jpg';
if( $time >= 19 && $time < 6 )
$img_name = 'night.jpg';
?>
<style>
.my-class{background-image:url('http://yoursite.com/images/<?php echo $img_name;?>');}
</style>
make sure you change url of the image correctly
Ross Gosling comments:
Thanks Arnav, this code works without needing the functions.php edit.
Hariprasad Vijayan answers:
Hello,
Try this method in your javascript
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
if (hours > 6 && hours <= 10){
document.body.style.backgroundImage="url('sunrise.jpg')";
} else if(hours > 10 && hours <= 17) {
document.body.style.backgroundImage="url('day.jpg')";
} else if(hours > 17 && hours <= 19) {
document.body.style.backgroundImage="url('sunset.jpg')";
} else {
document.body.style.backgroundImage="url('night.jpg')";
}
</script>
John Cotton answers:
$current_hour = intval( date('H') );
switch( $current_hour ) {
case ( $current_hour >= 6 && $current_hour < 10 ):
$class = "6_10";
break;
case ( $current_hour >= 10 && $current_hour < 17 ):
$class = "10_5";
break;
case ( $current_hour >= 17 && $current_hour < 19 ):
$class = "5_7";
break;
default:
$class = "7_6";
break;
}
That creates a class for you, then just use body_class with the actual background set as a series of classes in your css.