The Options API in WordPress is one of the many WordPress APIs we all use every day when developing with WordPress. A quick call to get_option() is not an uncommon sight. What if you could dynamically filter those options? You can.
Adding filters in WordPress is also a common practice. Combining this with the Options API can allow for, for example, the ability to change an option when in preview mode without committing to the change.
In the “Magazine” template in Canvas by WooThemes, for example, WooTumblog “image” and “video” posts are aware when they are present in the magazine-style grid. This is an example of filtering the Options API.
How do I use this?
Filtering the Options API is as easy as compiling any other filter. The filter hook is as follows: “option_optionname” (replace “optionname” with the name of the option you want to filter).
That filter is applied after the database lookup. What about before that even happens?
It is possible to short-circuit an option’s value using a second filter that has been made available. This means it’s possible to set a custom value, via a filter, for an option, bypassing the database lookup. My thoughts are packed with ideas for where to use this filter!
To short-circuit an option called, for example, “testoption”, you’d add the following code to your functions.php file:
add_filter( 'pre_option_testoption', 'matty_shortcircuit_options' );
function matty_shortcircuit_options ( $default ) {
$value = 'this is a short-circuited option';
return $value;
} // End matty_shortcircuit_options()
Using the “testoption” example again, this is how you’d override the value after it’s been retrieved from the database:
add_filter( 'option_testoption', 'matty_override_options' );
function matty_override_options ( $value ) {
$value = 'this is an overridden option';
// To override based on a condition, do this.
if ( $value == 'test' ) {
$value = 'this is an overridden option, based on a condition.';
}
return $value;
} // End matty_override_options()
This is just, however, a starting point as to how to do this. The possibilities are virtually limitless as to what is possible here and how to apply this in your projects.