0

I am looking for hooks that fire when inside of Appearance -> Widgets:

  • A widget gets added to a widget area
  • A widget gets deleted from a widget area
  • Widgets are being rearranged to new positions
  • A widget is being saved

I am looking to trigger a callback function after any of these events occur. My callback function simply triggers the purge cache function of the caching plugins I am using.

So far I have only found a hook called delete_widget, which gets triggered when a widget is being deleted.

add_action( "delete_widget", "my_function_purge_cache" , 10, 3); This works as intended.

However I can't find hooks for the other 3 events.

Reading through class-wp-widget.php I can see widgets use update_option to save any changes made to the widgets, including adding, removing, reordering and saving a widget.

update_option does have a hook called updated_option which fires after a setting has been successfully updated. I tested this hook using:

add_action( 'updated_option', 'my_function_purge_cache', 10, 3 ); and it seems to work as expected. My function is being called on all 4 events that I was looking for. However this might be an overkill as this gets triggered whenever any option is updated across WordPress and I have no idea how often this occurs. Worst case some 3rd party plugin calls update_option during each page visit.

2
  • Just check the option name inside the updated_option callback and only purge if it’s updating widgets. Feb 25, 2023 at 5:11
  • Thank you. That's what I ended up doing.
    – Kevin M
    Feb 25, 2023 at 14:43

1 Answer 1

0

I ended up using the updated_option hook and checking if a widget or sidebar has been updated.

When a widget is added, removed or saved, the update_option hook is fired.

All widget option names start with "widget_". By checking if the option name starts with "widget_" we can determine if a widget was added, removed or saved.

When widgets are being reordered within a widget area, the new positions are being saved to the option sidebars_widgets.

The hook updated_option fires immediately after an option has been successfully updated. Note: updated_option will not fire if the old value and the new value are the same.

function purge_cache_on_widget_change( $option, $old_value, $value ) {
    if( substr( $option, 0, 7 ) === 'widget_' || $option === 'sidebars_widgets' ) {
        my_function_purge_cache();
    }
}
add_action('updated_option','purge_cache_on_widget_change', 10, 3);

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.