I'm currently trying to get an option and if it's not present, simply assign an empty array as this variable:

$option = get_option( 'option_name' ) ? get_option( 'option_name' ) : [];

The problem is that not only is this ugly when the option name gets a little bit complicated, but I'm making the same call twice.

What are my options here?

One way would be:

$option = get_option( 'option_name' );

//If there is something in that $option and it's an array
if( $option !== null && is_array( $option ) ) {
    //Proceed with logic.

But this also seems rather complicated. Please keep in mind that I write for PHP 5.4, so ?? is out of the question.


You're not actually querying the database twice, if that's what you're worried about.

Regardless, as you'll see from the documentation, get_option() has a second argument you can use to define a default value for if the option hasn't been set:

$option = get_option( 'option_name', [] );
| improve this answer | |
  • Lawd Jesus, sometimes you forget to actually look at the documentation for the simplest of things. Would you mind explaining to me what you meant by "not querying twice"? I'm assuming WP has some inner processes that detects that it already pulled that option from the database before and no other changes occured, so it'll serve from a cache. – coolpasta Nov 12 '18 at 14:18
  • 1
    @coolpasta Check this line in the source code, wp_cache_get() does the caching, so no options query has to happen multiple times for multiple calls – kero Nov 12 '18 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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