The Obscure WordPress Get_option Parameter

Any WordPress Plugin developer worth their salt knows about the get_option function, which allows options to be retrieved from the database. What I recently discovered is that this function accepts a second parameter, indicating a default value to be returned if the option doesn’t exist in the database.

Here’s a simple example of the “old” and “new” ways of retrieving options from the database:

old:

1
2
3
4
$option = get_option( 'Option Name' );
if( false === $option ) {
$option = 'My real option value.';
}

new:

1
$option = get_option('option_name', 'default');

As you can see, this simplifies option retrieval and makes your code just a little easier to read.

EDIT: Thanks Nick Ohrn for pointing out a bug in the first code snippet. I’ve updated it so nobody is confused.

I am now accepting new clients for part-time consulting and software development projects. Learn more

I haven't configured comments for this blog, but if you want to get in touch, you can find me on Twitter