6

I would like to hook into a widget instance after it is removed from a sidebar panel on the Appearances -> Widgets admin page.

So if the instance was an active widget and then removed, I would like to hook into that instance before it is removed.

Can it be done?

1 Answer 1

5

Yes, this can be done. Ultimately, adding and removing a widget to/from a sidebar means updating an option in the database with a call like this:

update_option( 'sidebars_widgets', array( ... ) )

If you look at the code of update_option you see that there is a filter called just before the actual update. So if you want to do something before a widget is removed you can hook into:

add_filter ('pre_update_option_sidebars_widgets','wpse71075_pre_remove_widget',10,3);

At this point you only know that the list of active widgets is going to change, not whether it is addition or a removal. However, you do have $value and $old_value of the option, which you can compare inside your filter function (an array_search for a widget's label might be enough).

Read the answer to this question to learn about the structure of the sidebars_widgets option. It depends on your goal what you actually want to detect and do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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