函数文档

get_option()

💡 云策文档标注

概述

get_option() 是 WordPress 核心函数,用于根据选项名称检索选项值。它处理数据库查询、缓存机制和类型转换,并支持默认值和过滤器钩子。

关键要点

  • 函数签名:get_option( $option, $default_value = false ),其中 $option 为选项名称(字符串,无需 SQL 转义),$default_value 为可选默认值(默认为 false)。
  • 返回值:选项值(可为任意类型,包括标量、null、数组、对象)。若选项不存在且未提供默认值,返回 false;否则返回默认值。
  • 类型处理:非标量值(如数组)序列化存储后返回原类型;标量和 null 值通常转换为字符串返回,但存在例外情况(如使用过滤器或刚保存后)。
  • 缓存机制:优先从 alloptions 缓存加载,其次检查 notoptions 和 options 缓存,最后查询数据库并缓存结果以提高性能。
  • 过滤器钩子:支持 pre_option_$option、default_option_$option、option_$option 和 pre_option 等钩子,允许在检索前后修改值。
  • 常用选项:列举了 admin_email、blogname、siteurl 等常见选项名称,但实际可用选项取决于插件和配置。

代码示例

// 检查不存在的选项
$no_exists_value = get_option( 'no_exists_value' );
var_dump( $no_exists_value ); // 输出 false

$no_exists_value = get_option( 'no_exists_value', 'default_value' );
var_dump( $no_exists_value ); // 输出 'default_value'

// 使用过滤器修改选项值
add_filter( 'option_active_plugins', function( $plugins ) {
    return [];
});
var_dump( get_option('active_plugins') ); // 输出空数组

注意事项

  • 避免使用 false 作为初始化检查,应使用 add_option() 防止覆盖现有选项,以减少数据库查询。
  • 选项值可能因过滤器或保存时机而类型变化,开发时需注意类型一致性。
  • 对于多站点网络选项,应使用 get_site_option() 而非 get_option()。
  • 使用 Settings API 时,选项行可能直到表单提交才创建,默认值可能被返回而非 false。

📄 原文内容

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:

  1. When the option has not been saved in the database, the $default_value value is returned if provided. If not, boolean false is returned.
  2. 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.
  3. 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 returns string(0) ""
  • true returns string(1) "1"
  • 0 returns string(1) "0"
  • 1 returns string(1) "1"
  • '0' returns string(1) "0"
  • '1' returns string(1) "1"
  • null returns string(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

$optionstringrequired
Name of the option to retrieve. Expected to not be SQL-escaped.
$default_valuemixedoptional
Default value to return if the option does not exist.

Default:false

Return

mixed Value of the option. A value of any type may be returned, including scalar (string, boolean, float, integer), null, array, object.
Scalar and null values will be returned as strings as long as they originate from a database stored option value. If there is no option in the database, boolean false is returned.

More Information

A concise list of commonly-used options is below.

  • 'admin_email' – E-mail address of blog administrator.
  • 'blogname' – Weblog title; set in General Settings.
  • 'blogdescription' – Tagline for your blog; set in General Settings.
  • 'blog_charset' – Character encoding for your blog; set in Reading Settings.
  • 'date_format' – Default date format; set in General Settings.
  • 'default_category' – Default post category; set in Writing Settings.
  • 'home' – The blog’s home web address; set in General Settings.
  • 'posts_per_page' – Maximum number of posts to show on a page; set in Reading Settings.
  • 'posts_per_rss' – Maximum number of most recent posts to show in the syndication feed; set in Reading Settings.
  • 'siteurl' – WordPress web address; set in General Settings. Warning: This is not the same as get_bloginfo( 'url' ) (which will return the homepage url), but as get_bloginfo( ‘wpurl’ ).
  • 'template' – The current theme’s name.
  • 'start_of_week' – Day of week calendar should start on; set in General Settings.
  • 'upload_path' – Default upload location; set in Media Settings.
  • 'users_can_register' – Whether users can register; set in General Settings.

There are many more options available, a lot of which depend on what plugins you have installed.

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 any existing option before it is retrieved.
	 *
	 * Returning a value other than false from the filter will short-circuit retrieval
	 * and return that 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
	 * @since 3.0.0
	 * @since 4.4.0 The `$option` parameter was added.
	 *
	 * @param mixed  $value  Value of the option. If stored serialized, it will be
	 *                       unserialized prior to being returned.
	 * @param string $option Option name.
	 */
	return apply_filters( "option_{$option}", maybe_unserialize( $value ), $option );
}

Hooks

apply_filters( “default_option_{$option}”, mixed $default_value, string $option, bool $passed_default )

Filters the default value for an option.

apply_filters( “option_{$option}”, mixed $value, string $option )

Filters the value of an existing option.

apply_filters( ‘pre_option’, mixed $pre_option, string $option, mixed $default_value )

Filters the value of any existing option before it is retrieved.

apply_filters( “pre_option_{$option}”, mixed $pre_option, string $option, mixed $default_value )

Filters the value of an existing option before it is retrieved.

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 20 content

    A quick tip that the output of get_option() is filterable:

    return apply_filters( "option_{$option}", maybe_unserialize( $value ), $option );

    So you can change the output of get_option() at run time.

     //Outputs an array of all plugins
     var_dump( get_option('active_plugins') );
    
     add_filter( 'option_active_plugins', function( $plugins ){
    	return [];
    });
    
    //Outputs an empty array
    var_dump( get_option('active_plugins') );

    Helpful for disabling specific plugins when required.

    https://developer.wordpress.org/reference/hooks/option_option/

  2. Skip to note 21 content

    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.

    function comment_author_url_render() {
    
    	$options = get_option( 'plugin_settings' );
    	?>
    	<input type='checkbox' name='plugin_settings[setting]' <?php checked( isset( $options['setting'] ) ); ?> value='1'>
    	
    	</pre>
    <p>Hope this helps somebody else out.</p>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-3230' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_option%2F%3Freplytocom%3D3230%23feedback-editor-3230" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-2641" data-comment-id="2641" class="comment byuser comment-author-anuragthn odd alt thread-odd thread-alt depth-1">
    			<article id="div-comment-2641" class="comment-body">
    
    							<a href="#comment-content-2641" class="screen-reader-text">Skip to note 22 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/anuragthn/" rel="external nofollow" class="url">Anurag soni</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/functions/get_option/#comment-2641">
    							<time datetime="2018-04-10T11:30:38+00:00">
    							8 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="0f4025b1aa" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="2641" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_option%2F%23comment-2641"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title="75% like this"><span class="screen-reader-text">Vote results for this note: </span>2</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="2641" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_option%2F%23comment-2641"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-2641">
    				<p>Just like we use </p>
    <pre class="wp-block-code"><code lang="php" class="language-php ">get_option('date_format')

    to incorporate the date format defined in Settings -> General,

    We can also use

    get_option('time_format')

    to incorporate the time format defined in Settings -> General.

    for example

  3. Skip to note 24 content

    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.

    $wpdevref_text_2 = esc_attr( get_option( 'wpdevref_options' )['wpdevref_text_field_2'] );

    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

    $options = get_option('wpdevref_options'); 
    $wpdevref_text_2 = (empty($options['wpdevref_text_2'] )) 
                     ? 'Default Text' : $options['wpdevref_text_2']; 

    Alternatively (if default required):

    $wpdevref_text_2 = (empty( get_option( 'wpdevref_options' )['wpdevref_text_field_2']) )
                     ? 'Default Text' : get_option( 'wpdevref_options' )['wpdevref_text_field_2'];

    And for a checkbox in a settings array, try:

    'value'   => get_option('wpdevref_fields')['wpdevref_dashnews_widgetcheck'],
    'checked' => esc_attr( checked( 1, 
                 get_option('wpdevref_fields')['wpdevref_dashnews_widgetcheck'], false ) );

  4. Skip to note 25 content

    This is helpful for assigning defaults values to multiple options:

    /**
     * Retrieves multiple options values as an associative array based on an option name.
     * @param string $option_name (Required) Name of option to retrieve.
     * @param array $defaults (Optional) Default values to return if the option does not exist.
     */
    function wporg_prfex_get_theme_option( $option_name, $defaults = array() ) {
      $options = get_option( $option_name );
      //checking if options exists
      if ( ! empty( $options ) ) {
        $it = new MultipleIterator();
        $it->attachIterator( new ArrayIterator( $options ) );
        $it->attachIterator( new ArrayIterator( $defaults ) );
    
        foreach ( $it as $setting_name => $value ) {
          if ( empty( $value[0] ) ) {
            $optionsArray[ $setting_name[1] ] = $value[1];
          } else {
            $optionsArray[ $setting_name[0] ] = $value[0];
          }
        }// end loop
        return $optionsArray;
      } else {
        // if no options then set the defaults
        $optionsArray = $defaults;
        return $optionsArray;
      }
    }

    Usage as the following:

    $defaults = array(
          'settings_name1' => 'rgba(255, 0, 0, 0.7)',
          'settings_name1' => 'rgba(31, 200, 219, 0.7)',
          'settings_name1' => 'rgba(44, 181, 232, 0.7)'
        );
    $colors = wporg_prfex_get_theme_option( 'option_name', $defaults );

    Displaying the option:

    echo $colors['settings_name1'];

  5. Skip to note 26 content

    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:

    get_option( 'key_name', 'default_value' )

    So, if option value not set or avaiable than default value assigned to variable.

    Sample code:

    $my_plugin_version = get_option('plugin_name_version', '2.0');
    if($my_plugin_version == '1.0') {
    	// do something or apply changes and update the plugin version into option value
    } else {
    	// do nothing
    }

  6. Skip to note 28 content

    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.

  7. Skip to note 29 content

    To preserve the original type of a scalar option, deliberately wrap it, and any default value, in an array literal to force serialization + unserialization:

    $option = 'my_opt';
    $value = 87;
    update_option( $option, array( $value ), false );
    ...
    $default = 0;
    $wrapped_value = get_option( $option, array( $default ) );
    if ( ! is_array( $wrapped_value ) ) {
    	throw new Exception( 'Failed to get option.' );
    }
    list( $value ) = $wrapped_value;

  8. Skip to note 30 content

    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

    $checkbox = get_option('options');
    
        if ( isset( $checkbox['check_box'] ) ) {
            echo 'value exists- so return checked box ';
        } else {
            echo ' no value  - so return unchecked box ';
        }