WordPress Tip: Obscure 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:
$option = get_option( 'Option Name' );
if( false === $option ) {
$option = 'My real option value.';
}
new:
$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.
There’s a bug in your first example
What if the value of your option is 0 or an empty string.
$option = get_option( 'Option Name' );if( false === $option ) {
$option = 'My real option value.';
}
I do agree, though, that the improved get_option available with WP 2.7 makes things simpler. No more checking for false.
Very cool Will, I hate writing extra code for situations where the option isn’t set yet. I had no idea about this.
@Nick Good call! This makes the optional parameter even better