Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

What is the method to test for the existence of an option in the database?

Not the value of the option, just that the option exists.

share|improve this question

3 Answers 3

up vote 4 down vote accepted

Options that don't exist get the fact of their non-existence cached in memory when you attempt to get them. So you can check that cache to determine the difference.

$value = get_option('example');
$notoptions = wp_cache_get( 'notoptions', 'options' );
if ( isset( $notoptions['example'] ) ) {
    // option does not exist
} else {
    // option exists, $value is legit
}
share|improve this answer

That's a pretty good question!

Basically you can do several things to get around it, but the most easy is to check if your option is one of the array keys in the "autoloaded" options.

Take a look at add_option()s definition: The 4th argument is yes, which says "Add me to the autoloaded options".

If this is the case, you can simply check the array keys like in the following example:

function wpse65658_check_autoload_option( $opt_name )
{
    if ( in_array( 
         $opt_name
        ,array_keys( wp_load_alloptions() )
    ) ) 
        return true;

    return false;
}
share|improve this answer

Alternately,you could pass NULL as the default to get_option(), and then test for it:

if ( NULL === get_option( $option, NULL ) ) {
    // Option value is NULL;
    // do something
}

The reason I suggest using NULL as the default rather than false, is that some options may legitimately return a Boolean value, but should never legitimately return NULL.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.