Is there a way to allow only certain type of widgets in the sidebars?

It is possible to hook to sidebars_widgets and find which widget is in which sidebar.

function dump_sidebar($a) {
  echo '<pre>'.var_export($a,true).'</pre>';
}
add_action( 'sidebars_widgets', 'dump_sidebar');

By checking that array you could eliminate particular widgets.

function limit_sidebar_wpse_101279($sidebars_widgets) {
  if (!empty($sidebars_widgets['sidebar-1'])) {
    foreach ($sidebars_widgets['sidebar-1'] as $k =>$v) {
      if ('pages' == substr($v,0,5)) {
        unset($sidebars_widgets['sidebar-1'][$k]);
      }
    }
  }
  return $sidebars_widgets;
}
add_action( 'sidebars_widgets', 'limit_sidebar_wpse_101279');

That works front end, and back end, but does not prevent a widget from being dragged into the wrong sidebar on the back end. That is, you can still drag a widget into the wrong sidebar and have it appear to work, but it will be removed on next page load. To solve that issue you will need to construct some Javascript to prevent the drag or issue some kind of warning.

Leave a Comment