How to tell if an option has been created vs an empty option?

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.

Related posts

Leave a Reply

3 comments

  1. 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
    }
    
  2. 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.

  3. 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;
    }