I have several sidebars in the theme I'm developing. Some of them are designed to hold only a few widget types. So I'm trying to figure out how to keep other widgets out without using a plugin.
After a lot of googling, I believe there are only 2 options:
- Use jquery on widgets admin page to prevent dragging & dropping of certain widgets to certain widget areas. In a perfect world, the user will see some sort of message saying that this particular widget is not allowed in this particular widget area.
- Use wp 'sidebars_widgets' filter to remove widgets server side.
First sounds like a better way, mostly performance wise. What do you think? Although, I failed to find any working solution and my jquery knowledge is not enough. Sadly, my PHP knowledge obviously also is not enough to nail the sceond solution. Here's what I have:
add_filter( 'sidebars_widgets', 'wp150734_code_disable_widgets' );
function wp150734_code_disable_widgets( $sidebars_widgets ) {
// This code works for one sidebar & one widget :
$allowed_widget = 'wp150734_widget_social';
$sidebar_to_check = 'wp150734_widgets_navbar';
// But I want to check the array of sidebars with allowed widgets:
$sidebars_to_check = array(
// allowed widgets in 'wp00734_widgets_navbar'
'wp150734_widgets_navbar' => array(
'widget_search',
'widget_text',
'wp150734_widget_social'
),
// allowed widgets in 'wp00734_widgets_footer'
'wp00734_widgets_footer' => array(
'widget_search',
'widget_text',
'wp00734_widget_social'
)
);
foreach ( $sidebars_widgets as $sidebars_key=>$sidebars_widget ) {
// Check if we even need to check this sidebar
if ( $sidebars_key != $sidebar_to_check )
continue;
if ( $sidebars_widget ) {
foreach ( $sidebars_widget as $k=>$v ) {
// Look for our custom widget and unset all other widgets from the $sidebars_widgets array
if ( stripos( $v, $allowed_widget ) === false ) {
unset( $sidebars_widgets[$sidebars_key][$k] );
}
}
}
}
return $sidebars_widgets;
};
What do you guys think? I'm feeling like jquery solution would be better, but can't find anything related.
EDIT: I have 2-3 custom widgets in addition to all the standard. I want all those widgets to work normally in all registered widget areas. Now I have a top navbar in the theme. It's designed to hold some data. Like menus, social icons, search and text in the chosen order. Since I already have all that in the form of widgets that can be reordered, it sounds like a logical idea to register a custom widget area in the navbar and let the user chose widgets and reorder them. No need to duplicate the functionality - widgets already offer it out of the box. The only problem is that not all widgets are designed to sit in the navbar.