Skip to content

Instantly share code, notes, and snippets.

@verygoodplugins
Last active May 29, 2020 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save verygoodplugins/13c6466c2306068536fc0e6da62d8efb to your computer and use it in GitHub Desktop.
Save verygoodplugins/13c6466c2306068536fc0e6da62d8efb to your computer and use it in GitHub Desktop.
Simple snippet for adding a checkbox to hide widgets from logged in users
<?php
// Widget form
function cust_widget_form( $widget, $return, $instance ) {
if( ! isset( $instance['logged_out_only'] ) ) {
$instance['logged_out_only'] = false;
} ?>
<p>
<input name="<?php echo $widget->get_field_name('logged_out_only'); ?>" type="checkbox" value="1" <?php checked( $instance['logged_out_only'], 1 ); ?> />
<label>Hide from logged in users</label>
</p>
<?php
}
add_action( 'in_widget_form', 'cust_widget_form', 10, 3 );
// Save widget
add_filter( 'widget_update_callback', function( $instance, $new_instance ) {
if( isset( $new_instance['logged_out_only'] ) ) {
$instance['logged_out_only'] = $new_instance['logged_out_only'];
} else {
unset( $instance['logged_out_only'] );
}
return $instance;
}, 10, 2 );
// Hide widget
add_filter( 'widget_display_callback', function( $instance ) {
if ( ! empty( $instance['logged_out_only'] ) && is_user_logged_in() ) {
return false;
}
return $instance;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment