I am working on a WordPress plugin to insert advertisements.Its also having a widget to show the ads.In my main plugin class I want to check for a condition and if it satisfies I want to delete a particular instance of the widget.

class Main_Plugin{
    if(//condition) {
         //delete widget instance

How to do it??Is it possible or I am going in the wrong direction?

  • Have a look at the sidebars_widgets filter I have used in this post – Pieter Goosen Apr 8 '16 at 7:31
  • @PieterGoosen, I think costumizer skips that filter :(, which is why I had to figure out the answer below – Mark Kaplun Apr 8 '16 at 8:30

Widgets should only be manipulated by users, and in general they should not be deleted because there is no version control for them. Therefor I suggest you rethink first before reading further.

Widgets are located in two places in the DB, the sidebar_widgets option is an array of sidebars, indexed by the sidebar id. Each sidebar is represented by an array of widget identifiers.

The individual widget settings are located at an option called widget_{widget name} which is an array indexed by the widget id of the widget.

So to removed some widgets of a specific type you need to do something like

$sidebars = get_option('sidebar_widgets');
$widgets  = get_option('widget'.your widget base name);
foreach ($sidebars as $sidebar_id => $sidebar) {
  foreach ($sidebar as $key=>$widget_id) {
    if ($widget_id match the name pattern of the widget type) {
      $widget = $widgets[$widget_id];
      if ($widget needs to be deleted)
        update_option('widget'.your widget base name, $widgets);
        update_option(`sidebar_widgets', $sidebars);

obviously you can start with locating the widget id in the widget's option and then loop over the sidebar.

Obviously it is just meta code and some small details might need to be adjusted, but pay attention that the unset here is probably done in a not very safe way.

  • This actually worked but it deleted all the data from the DB.I just don't want that widget to be displayed on frontend. Don't want to completely delete all the the data.BTW its 'sidebars_widgets'. – Rony Mathew Apr 8 '16 at 13:09
  • hmmm, you used the word "delete" ;)if you want to hide then put the code in it that do not display it under some condition. – Mark Kaplun Apr 8 '16 at 13:30
  • Sorry:)yeah I think its the right way to day...Thanks for your quick responses. – Rony Mathew Apr 8 '16 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.