Time-of-Day Greeting Shortcode
Adds a [greeting] shortcode that says Good morning, Good afternoon or Good evening based on your site's timezone, with the logged-in user's first name when there is one.
Opens WPIDE on
Code
// Greetings and the hour each one starts (24-hour clock, in the timezone set under Settings > General).
// Between midnight and the first hour, the last greeting is used.
$wpide_greetings = array(
5 => 'Good morning',
12 => 'Good afternoon',
18 => 'Good evening',
);
add_shortcode( 'greeting', function ( $atts ) use ( $wpide_greetings ) {
$atts = shortcode_atts( array(
'name' => 'yes', // Add the logged-in user's first name.
'guest' => '', // Name used for visitors who are not logged in, e.g. "friend".
), $atts, 'greeting' );
$greetings = $wpide_greetings;
ksort( $greetings );
$hour = (int) wp_date( 'G' );
$greeting = (string) end( $greetings );
foreach ( $greetings as $start => $text ) {
if ( $hour >= (int) $start ) {
$greeting = (string) $text;
}
}
$name = '';
if ( 'yes' === strtolower( (string) $atts['name'] ) && is_user_logged_in() ) {
$user = wp_get_current_user();
$name = '' !== trim( $user->first_name ) ? $user->first_name : $user->display_name;
}
if ( '' === trim( $name ) ) {
$name = (string) $atts['guest'];
}
$name = trim( wp_strip_all_tags( $name ) );
return '<span class="wpide-greeting">' . esc_html( '' !== $name ? $greeting . ', ' . $name . '!' : $greeting . '!' ) . '</span>';
} );
Notes
Examples: [greeting], [greeting guest="friend"], [greeting name="no"]. Change the texts and start hours at the top. Page caching can show logged-out visitors a greeting from an earlier time of day.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.