Show Widgets Only to Logged-In or Logged-Out Visitors
Adds a "Show to" setting to every classic widget so you can display it to everyone, only to logged-in users, or only to visitors who are not logged in.
Opens WPIDE on
Code
add_action( 'in_widget_form', function ( $widget, $return, $instance ) {
$value = isset( $instance['wpide_visibility'] ) ? $instance['wpide_visibility'] : '';
$options = array(
'' => 'Everyone',
'logged_in' => 'Logged-in users',
'logged_out' => 'Logged-out visitors',
);
echo '<p><label for="' . esc_attr( $widget->get_field_id( 'wpide_visibility' ) ) . '">Show to:</label> ';
echo '<select class="widefat" id="' . esc_attr( $widget->get_field_id( 'wpide_visibility' ) ) . '" name="' . esc_attr( $widget->get_field_name( 'wpide_visibility' ) ) . '">';
foreach ( $options as $key => $label ) {
echo '<option value="' . esc_attr( $key ) . '"' . selected( $value, $key, false ) . '>' . esc_html( $label ) . '</option>';
}
echo '</select></p>';
}, 10, 3 );
add_filter( 'widget_update_callback', function ( $instance, $new_instance ) {
$value = isset( $new_instance['wpide_visibility'] ) ? sanitize_key( $new_instance['wpide_visibility'] ) : '';
$instance['wpide_visibility'] = in_array( $value, array( 'logged_in', 'logged_out' ), true ) ? $value : '';
return $instance;
}, 10, 2 );
add_filter( 'widget_display_callback', function ( $instance ) {
if ( ! is_array( $instance ) || empty( $instance['wpide_visibility'] ) ) {
return $instance;
}
if ( 'logged_in' === $instance['wpide_visibility'] && ! is_user_logged_in() ) {
return false;
}
if ( 'logged_out' === $instance['wpide_visibility'] && is_user_logged_in() ) {
return false;
}
return $instance;
} );
Notes
Works with classic widgets and the Legacy Widget block. Block widgets do not have the setting.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.