Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.