Archived topic
Widget only if user is logged in
7 replies · Started by Jörg on February 4, 2023
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!
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.
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!
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?
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.
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
It work's :-) Thank you!
Glad to hear that!