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

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

Leave a Comment