Conditional Text Depending on Time of Day in PHP
In working on one of my other sites, I searched all over for a script that would allow a dynamic adjustment of messages displayed, based on the time of day. I found a handful that were charging for such a script, so I decided to make my own!
Since many, or even most (depending on who you ask), websites for making money online are built around a core of the free and fantastic Open-Source software WordPress, a simple PHP function seemed the best way to handle this.
As you’ll see, the code is elegant and simple: and, by configuring it as a function, can easily be added to the functions.php (or a single file) file in your WordPress theme, without the hassle of installing YAP (Yet Another Plugin!) to be used throughout the rest of your WordPress theme — header, footer, sidebar, blah, blah, blah.
Drumroll, please (can you tell I’m proud of myself?)…
<?php
function timeofday($morning, $day, $night) {
$hour = date('G');
if (($hour > 0) && ($hour < 10)) { echo $morning; }
elseif (($hour > 9) && ($hour < 17)) { echo $day; }
else echo $night;
}
?>
In the above configuration, if the time on the server is 1am-9am it delivers the “morning” text. If it’s 10am-5pm, the script prints the “daytime” text. Otherwise, it displays the “night” text.
In this case, the “target audience” would be somewhere close to the same time-zone as the server. Otherwise, some more technical methods would be involved requiring Java to pick up the viewer’s timezone and pass the information to PHP, which I might cover later.
To use this function in your WordPress files, you can add the code above to the functions.php file of your theme, then insert the function where needed, just as you would any other function with parameters like bloginfo(), the_content(), etc.:
<?php timeofday('morning text', 'daytime text', 'evening text'); ?>
Hope this is helpful! It worked great for what I was trying to accomplish.











