Prevent widget from displaying programmatically
While developing the WooCommerce Members Only plugin, I wanted a way to ensure that widgets were only available for certain users. You can do this using theĀ widget_display_callback
filter – just return false
to prevent the widget content from being rendered.
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 | |
/** | |
* This will hide widgets | |
* @param array $instance The current widget instance's settings. | |
* @param WP_Widget $this The current widget instance. | |
* @param array $args An array of default widget arguments. | |
*/ | |
function wcmo_filter_widget_display_callback( $settings, $widget, $args ) { | |
$can_access = false; // You need to set your conditions here | |
if( $can_access || in_array( $widget->name, $whitelist ) ) { | |
// If the user can view the widget, just return the settings | |
return $settings; | |
} | |
// Otherwise, return false to prevent the widget from rendering | |
return false; | |
} | |
add_filter( 'widget_display_callback', 'wcmo_filter_widget_display_callback', 10, 3 ); |