Retrieves an option value based on an option name.
Description
If the option does not exist, and a default value is not provided, boolean false is returned. This could be used to check whether you need to initialize an option during installation of a plugin, however that can be done better by using add_option() which will not overwrite existing options.
Not initializing an option and using boolean false
as a return value is a bad practice as it triggers an additional database query.
The type of the returned value can be different from the type that was passed when saving or updating the option. If the option value was serialized, then it will be unserialized when it is returned. In this case the type will be the same. For example, storing a non-scalar value like an array will return the same array.
In most cases non-string scalar and null values will be converted and returned as string equivalents.
Exceptions:
- When the option has not been saved in the database, the
$default_value
value is returned if provided. If not, booleanfalse
is returned. - When one of the Options API filters is used: ‘pre_option_$option’, ‘default_option_$option’, or ‘option_$option’, the returned value may not match the expected type.
- When the option has just been saved in the database, and get_option() is used right after, non-string scalar and null values are not converted to string equivalents and the original type is returned.
Examples:
When adding options like this: add_option( 'my_option_name', 'value' )
and then retrieving them with get_option( 'my_option_name' )
, the returned values will be:
false
returnsstring(0) ""
true
returnsstring(1) "1"
0
returnsstring(1) "0"
1
returnsstring(1) "1"
'0'
returnsstring(1) "0"
'1'
returnsstring(1) "1"
null
returnsstring(0) ""
When adding options with non-scalar values like add_option( 'my_array', array( false, 'str', null ) )
, the returned value will be identical to the original as it is serialized before saving it in the database:
array(3) {
[0] => bool(false)
[1] => string(3) "str"
[2] => NULL
}
Parameters
$option
stringrequired- Name of the option to retrieve. Expected to not be SQL-escaped.
$default_value
mixedoptional- Default value to return if the option does not exist.
Default:
false
Source
function get_option( $option, $default_value = false ) {
global $wpdb;
if ( is_scalar( $option ) ) {
$option = trim( $option );
}
if ( empty( $option ) ) {
return false;
}
/*
* Until a proper _deprecated_option() function can be introduced,
* redirect requests to deprecated keys to the new, correct ones.
*/
$deprecated_keys = array(
'blacklist_keys' => 'disallowed_keys',
'comment_whitelist' => 'comment_previously_approved',
);
if ( isset( $deprecated_keys[ $option ] ) && ! wp_installing() ) {
_deprecated_argument(
__FUNCTION__,
'5.5.0',
sprintf(
/* translators: 1: Deprecated option key, 2: New option key. */
__( 'The "%1$s" option key has been renamed to "%2$s".' ),
$option,
$deprecated_keys[ $option ]
)
);
return get_option( $deprecated_keys[ $option ], $default_value );
}
/**
* Filters the value of an existing option before it is retrieved.
*
* The dynamic portion of the hook name, `$option`, refers to the option name.
*
* Returning a value other than false from the filter will short-circuit retrieval
* and return that value instead.
*
* @since 1.5.0
* @since 4.4.0 The `$option` parameter was added.
* @since 4.9.0 The `$default_value` parameter was added.
*
* @param mixed $pre_option The value to return instead of the option value. This differs from
* `$default_value`, which is used as the fallback value in the event
* the option doesn't exist elsewhere in get_option().
* Default false (to skip past the short-circuit).
* @param string $option Option name.
* @param mixed $default_value The fallback value to return if the option does not exist.
* Default false.
*/
$pre = apply_filters( "pre_option_{$option}", false, $option, $default_value );
/**
* Filters the value of all existing options before it is retrieved.
*
* Returning a truthy value from the filter will effectively short-circuit retrieval
* and return the passed value instead.
*
* @since 6.1.0
*
* @param mixed $pre_option The value to return instead of the option value. This differs from
* `$default_value`, which is used as the fallback value in the event
* the option doesn't exist elsewhere in get_option().
* Default false (to skip past the short-circuit).
* @param string $option Name of the option.
* @param mixed $default_value The fallback value to return if the option does not exist.
* Default false.
*/
$pre = apply_filters( 'pre_option', $pre, $option, $default_value );
if ( false !== $pre ) {
return $pre;
}
if ( defined( 'WP_SETUP_CONFIG' ) ) {
return false;
}
// Distinguish between `false` as a default, and not passing one.
$passed_default = func_num_args() > 1;
if ( ! wp_installing() ) {
$alloptions = wp_load_alloptions();
/*
* When getting an option value, we check in the following order for performance:
*
* 1. Check the 'alloptions' cache first to prioritize existing loaded options.
* 2. Check the 'notoptions' cache before a cache lookup or DB hit.
* 3. Check the 'options' cache prior to a DB hit.
* 4. Check the DB for the option and cache it in either the 'options' or 'notoptions' cache.
*/
if ( isset( $alloptions[ $option ] ) ) {
$value = $alloptions[ $option ];
} else {
// Check for non-existent options first to avoid unnecessary object cache lookups and DB hits.
$notoptions = wp_cache_get( 'notoptions', 'options' );
if ( ! is_array( $notoptions ) ) {
$notoptions = array();
wp_cache_set( 'notoptions', $notoptions, 'options' );
}
if ( isset( $notoptions[ $option ] ) ) {
/**
* Filters the default value for an option.
*
* The dynamic portion of the hook name, `$option`, refers to the option name.
*
* @since 3.4.0
* @since 4.4.0 The `$option` parameter was added.
* @since 4.7.0 The `$passed_default` parameter was added to distinguish between a `false` value and the default parameter value.
*
* @param mixed $default_value The default value to return if the option does not exist
* in the database.
* @param string $option Option name.
* @param bool $passed_default Was `get_option()` passed a default value?
*/
return apply_filters( "default_option_{$option}", $default_value, $option, $passed_default );
}
$value = wp_cache_get( $option, 'options' );
if ( false === $value ) {
$row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
// Has to be get_row() instead of get_var() because of funkiness with 0, false, null values.
if ( is_object( $row ) ) {
$value = $row->option_value;
wp_cache_add( $option, $value, 'options' );
} else { // Option does not exist, so we must cache its non-existence.
$notoptions[ $option ] = true;
wp_cache_set( 'notoptions', $notoptions, 'options' );
/** This filter is documented in wp-includes/option.php */
return apply_filters( "default_option_{$option}", $default_value, $option, $passed_default );
}
}
}
} else {
$suppress = $wpdb->suppress_errors();
$row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
$wpdb->suppress_errors( $suppress );
if ( is_object( $row ) ) {
$value = $row->option_value;
} else {
/** This filter is documented in wp-includes/option.php */
return apply_filters( "default_option_{$option}", $default_value, $option, $passed_default );
}
}
// If home is not set, use siteurl.
if ( 'home' === $option && '' === $value ) {
return get_option( 'siteurl' );
}
if ( in_array( $option, array( 'siteurl', 'home', 'category_base', 'tag_base' ), true ) ) {
$value = untrailingslashit( $value );
}
/**
* Filters the value of an existing option.
*
* The dynamic portion of the hook name, `$option`, refers to the option name.
*
* @since 1.5.0 As 'option_' . $setting
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
Handling of non-existing options
Show Blog Title
Displays your blog’s title in a
<h1>
tag.Show Character Set
Displays the character set your blog is using (ex: UTF-8)
Retrieve Administrator E-mail
Retrieve the e-mail of the blog administrator, storing it in a variable.
A quick tip that the output of
get_option()
is filterable:So you can change the output of
get_option()
at run time.Helpful for disabling specific plugins when required.
https://developer.wordpress.org/reference/hooks/option_option/
Check if option is set to avoid warnings.
Was getting Illegal Offset warnings when the checkbox was not selected on a plugin’s option page.
Adding isset() inside checked() sorted it all out.
Hope this helps somebody else out.
Just like we use
to incorporate the date format defined in Settings -> General,
We can also use
to incorporate the time format defined in Settings -> General.
for example
If you want to get a network-wide option, use the get_site_option function instead. https://developer.wordpress.org/reference/functions/get_site_option
There is a “long-hand” format for creating option settings-field parameter in one line that is harder to read/follow semantically, but provides a single string to a options setting instead of two strings for every option.
The above returns false, so technically there is no default to setup unless you require a value.
And there are just a bit less parameter parsing than
Alternatively (if default required):
And for a checkbox in a settings array, try:
This is helpful for assigning defaults values to multiple options:
Usage as the following:
Displaying the option:
Simply way to check the option value set or not.
For Example, I have a plugin version 1.0 that is installed on the user site. The plugin version is set on the plugin activation. If I released a new plugin version 2.0 and need to check the installed plugin version and new apply changes on the new version update.
For it, you need to set default value in function:
So, if option value not set or avaiable than default value assigned to variable.
Sample code:
For use with images includes a default image in child theme folder named default.png and option when adding image using the customizer.
$image = get_option( 'genesis-customizer-image', sprintf( '%s/default.png', get_stylesheet_directory_uri() ) );
Keep in mind that if you use Settings API along with Options API, the database row for the option will NOT be created until the setting page form is submitted with an updated value for that setting.
If a default value is set when registering your settings, and you try to test if the option exists, if there is no database entry for the option, the default value set with Settings API will be returned instead of
false
. Keep this in mind when writing your code.To preserve the original type of a scalar option, deliberately wrap it, and any default value, in an array literal to force serialization + unserialization:
check options exists or not, use isset to check
if value exists then checked box appear, if there is no option then unchecked box appears