Hide widget to non-logged in users without plugin (functions.php)

I am working on a Woocommerce WordPress site.

I want to hide a widget in frontend to non-logged in users.

Read More

The widget is “filter by price” from Woocommerce. I’m also using the “Catalog Visibility Options” because I am not able to show prices to non logged-in users.

I’m using canvas theme and a child theme.

I want to use a code to insert in my custom functions.php file.

I don’t want to use a plugin.

I was trying with this code, but I am not able to finish it:

// Hide Widget to non-logged user

function hide_widget() {
    if ( is_user_logged_in() ) {

    } else { 

    }
}

add_action( 'wp', 'hide_widget' );

Can somebody please assist me with this?

Thank you very much!!

Related posts

2 comments

  1. Tested on Twenty Fourteen and works.

    Change the loop_start hook to another position if needed.

    The code goes at the end of your child themes functions.php file.

    function wpsites_register_widget() {
    
     register_sidebar( array(
    'name' => 'Logged In Only Widget',
    'id' => 'members-widget',
    'before_widget' => '<div>',
    'after_widget' => '</div>',
    ) );
    }
    
    add_action( 'widgets_init', 'wpsites_register_widget' );
    
    add_action( 'loop_start', 'logged_in_widget', 25 );
    
    function logged_in_widget() {
    
    
        if ( is_user_logged_in() && is_active_sidebar( 'members-widget' ) ) { 
        dynamic_sidebar('members-widget', array(
        'before' => '<div class="members-widget">',
        'after' => '</div>',
    ) );
    
          }
    
    }
    

    Another solution is to use a widget logic type plugin where you can add the conditional is_user_logged_in() to the existing widget.

    http://codex.wordpress.org/Function_Reference/is_user_logged_in
    https://wordpress.stackexchange.com/a/128181/9884

  2. FInd out where the widget is being called and wrap like this:

          if ( is_user_logged_in() ) { 
               dynamic_sidebar( 'WIDGET' );
          }
    

Comments are closed.