PHP: Welcome users to your website with a time-based message

I've created a little PHP function called GreatTheUser that takes the user's name as input and returns a customised greeting based on the time of day. The function uses WordPress' wp_date function to retrieve the current time and match expressions to select the appropriate greeting.

function GreatTheUser($name) {
$date = (wp_date('H'));
return match (true) {
($date < 10) => sprintf(__('Good morning %s', SLUG), $name),
($date < 12) => sprintf(__('Good morning %s', SLUG), $name),
($date < 17) => sprintf(__('Good afternoon %s', SLUG), $name),
($date < 20) => sprintf(__('Godaften %s', SLUG), $name),
default => sprintf(__('Welcome %s', SLUG), $name),
};
}

Here's how the feature works:

  • The PHP function, which I call GreatTheUser, takes the user's name as input.
  • Using WordPress' wp_date function I retrieve the current hour, you can also date('H').
  • I then use the match expression to assess the time of day and select the appropriate greeting.
  • The greeting contains the user's name and adapts to morning, midday, afternoon, evening or uses a default greeting if no conditions are met.