Filtering the Options API in WordPress

The Options API in WordPress is one of the many APIs we all use every day when developing with WordPress. A quick use of get_option() is not uncommon. What if you could filter those options? You can.

Adding filters in WordPress is also a common practice. Combining this with the Options API can allow for, as an example, changing an option when in preview mode without committing to the change.

In the “Magazine” template in the Canvas theme 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 WordPress filter?

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 different filter that’s available. This means it’s possible to set a custom value for an option, via a filter and bypass 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.

WordPress tips in your inbox ✨

More WordPress thoughts and tips, right in your inbox.

We don’t spam! Read our privacy policy for more info.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *