• The code below is an attempt to create a shortcode to display the user name that I have placed in the header. It mostly works, but when going to a new page, the logged in user is not found by the shortcode, and shows ‘Not logged in’, unless I do a manual refresh.

    function custom_shortcode_func()
    {
        ob_start();
        $current_user = wp_get_current_user();
        if ( is_user_logged_in() )
        {
            $current_user = wp_get_current_user();
            echo $current_user->display_name;
        }
        else
        {
            echo 'Not logged in';
        }
        $output = ob_get_clean();
        return $output;
    }

    add_shortcode('current_user', 'custom_shortcode_func');

    I have tried messing around with various cache plugins, turning the cache on/off, etc, but did not have any luck. The website link is for a simple test setup to demonstrate the problem. It was created on Bluehost with the latest WordPress and php.

    Thanks in advance for any help or suggestions.

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • This should work reliably without any caching plugins. Have you tried it like this?

    However, one problem could be ob_start(). I would rather write the code like this:

    function custom_shortcode_func() {
    if ( is_user_logged_in() ) {
    $current_user = wp_get_current_user();
    return esc_html( $current_user->display_name );
    }
    return 'Not logged in';
    }
    add_shortcode('current_user', 'custom_shortcode_func');

    In this way, it also complies with WordPress coding standards.

    Thread Starter michaeljgibson

    (@michaeljgibson)

    Hi threadi, Thank you for the fast response. Unfortunately, your suggestion does not work for me on the Bluehost test website. However I tried a simple local install with the same setup and it appears to work just fine in that case. So I am now assuming Bluehost is the problem and will try another hosting platform.

    Thread Starter michaeljgibson

    (@michaeljgibson)

    Just a follow up on this, I tried the same test on IONOS, and it worked just fine. So, I have to say the problem is with Bluehost, but unfortunately, I cant say anything more specific than that.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.