Site logo

[Resolved] Widget only if user is logged in

Home Forums Support [Resolved] Widget only if user is logged in

Home Forums Support Widget only if user is logged in

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #2521339
    Jörg

    I would like to display the name of the logged-in user in a widget in the sidebar. If nobody is logged in, the widget should not be displayed. How can I realize this with GeneratePress?

    Many thanks!

    #2521371
    David
    Staff
    Customer Support

    Hi there,

    you could create yourself a simple Shortcode by adding a PHP Snippet to your site:

    add_shortcode('hello_user', function(){
        $html = '';
        $prefix = 'Message before username: ';
        global $current_user; 
        wp_get_current_user();
        if ( is_user_logged_in() ) {
            $html = $prefix . $current_user->display_name;
        }
        return $html;
    });

    This doc explains how to add PHP: https://docs.generatepress.com/article/adding-php/

    Then you can add the [hello_user] shortcode to your sidebar widget or using a GP Element.

    #2521472
    Jörg

    Thank’s for your reply 🙂

    The shortcode works. But if user logged out, the widget ist also visible as a “placeholder” (https://tanzsport-schwedt.de, 4. Widget on right sidebar). It shold not be visible, if user logged out.

    Thank you for your help!

    #2521605
    Ying
    Staff
    Customer Support

    Hi Jorg,

    Should all 4 widgets not appear when the user’s logged out?

    Does that mean you don’t need a sidebar when the user’s logged out?

    #2521841
    Jörg

    The sidebar should not be deactivated when the user is logged out. Just the widget that displays the name of the logged in user.

    Similar to the function of the Woocommerce shopping cart widget, which is only displayed if there is at least one item in it.

    #2521967
    David
    Staff
    Customer Support

    Where in the sidebar will the widget be displayed?
    If it is at the top or the bottom of the sidebar, then instead of using a Widget, use a Block Element:

    https://docs.generatepress.com/article/block-element-hook/

    In the list of hooks, there are ones for the sidebars, before and after.

    You can add whatever content you want there including the shortcode.
    And then set the elements display rules -> User to Logged in.

    Let me know if thats a solution

    #2522065
    Jörg

    It work’s 🙂 Thank you!

    #2522080
    David
    Staff
    Customer Support

    Glad to hear that!

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