# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: content, shortcode, personalization
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/time-of-day-greeting-shortcode/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Time-of-Day Greeting Shortcode" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
