How to Retrieve an Option in WordPress

Say you have a feature that you’d like to be able to enable/disable at any time. One way to do this is by saving an option in the _options table and then checking its value to see if the feature is active or not. We can check this by using get_option() which is a simple function for checking option values but it does have some quirks.

First, it will only return strings. So setting true will not pass a strict comparison evaluation like this:

if ( get_option( 'option_name' ) === true )

We would actually have 1 returned which won’t match so the condition will be false even though true is saved in the option itself.

if ( get_option( 'option_name' ) === 'true' ) 

To compare it, we would need to set the comparison to a string like this:

if ( get_option( 'option_name' ) === 'true' )

// or 

if ( get_option( 'option_name' ) === '1' )

Second, you can also pass a default value with get_option. This will actually add the default as a new option if it doesn’t already exist.

if ( get_option( 'option_name', 'true' ) === 'true' ) 

Third, the default value won’t be saved if it evaluates to false. So while the code above will create a new row with a value of 'true'this code won’t alter the options table at all.

if ( get_option( 'option_name', 'false' ) === 'true' ) 

So now you know how to save an option to the WordPress _options table and a few of the quirks that go along with this.

Leave a Reply

%d bloggers like this: