Updating options within the WordPress admin is simple, right? It’s a matter of filling out a text field, checking a box, or swapping a radio button then clicking save.
But let’s say that you need to set up a hook that fires that also updates a secondary, related option whenever one is toggled.
For example, given an option represented by a checkbox, let’s say that you want to set an option in the database whenever the checkbox is unchecked and then delete it whenever said option is set.
There’s an action specifically for doing this that makes it pretty easy.
A Hook for Updating Options
Before getting into any code for how to do this, say that the given update_option has been tripped. One done, you’ll need to setup a callback that fires whenever the option is set.
On top of that, there are the following considerations:
- Was the option in question toggled?
- If so, was the option set (assuming it was a checkbox)?
- If not, do you have a plan for how to handle that case?
Assuming all of the above has been figured out, you’ll need a function to define the action and a function that implements the callback. In my example, I’ll be using object-oriented programming, but it can be done just as well in procedural programming.
In my example, I’ll be using object-oriented programming, but it can be done just as well in procedural programming.
An Example
Say you have an option called user_is_disguised, and you have another value in the database called user_is_superman.
Whenever user_is_disguised is set to yet, then user_is_superman should be set to false. And then when user_is_disguised is set to false, user_is_superman should be set to true.
Ultimately, the values swap. Here’s an example how to do it. First, we need to setup the hook:
Then we need to implement the function for swapping the values:
And that should take care of it.
A Note About Arguments
Notice that the callback accepts three arguments (which are also defined in the documentation linked above). These are useful in other, less contrived implementations.
But perhaps one of the most important things to take away from the code above is that you check the option name in the callback before toggling any values.