Last active
May 29, 2020 13:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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