get_option

函数
get_option ( $option, $default = false )
参数
  • (string) $option Name of the option to retrieve. Expected to not be SQL-escaped.
    Required:
  • (mixed) $default Optional. Default value to return if the option does not exist.
    Required:
    Default: false
返回值
  • (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.
定义位置
相关方法
get_alloptionsget_blog_optionget_site_optionget_user_optiondelete_option
引入
1.5.0
弃用
-

get_option函数是一个WordPress函数,它从数据库中检索一个选项值。WordPress中的选项是可以由用户设置和调整的设置: 这个函数接受一个参数,它是你想检索的选项的名称。例如,如果你想检索”blogname”选项的值,你会调用get_option(‘blogname’): 该函数返回该选项的值。

检索基于选项名称的选项值。

如果该选项不存在,并且没有提供默认值。会返回布尔值false。这可以用来检查你是否需要 在安装插件的过程中初始化一个选项,然而这 可以通过使用add_option()更好地完成,它将不会覆盖 现有的选项。

不初始化一个选项并使用布尔值”false”作为返回值 是一个不好的做法,因为它会触发一个额外的数据库查询。

返回值的类型可以与保存或更新选项时传递的类型不同。时传递的类型不同。如果选项的值被序列化了。那么当它被返回时,它将被取消序列化。在这种情况下,其类型将 是相同的。例如,存储一个像数组一样的非标量值会 返回相同的数组。

在大多数情况下,非字符串的标量值和空值将被转换并返回 作为字符串的等价物。

例外的情况:

1. 当选项没有保存在数据库中时,如果提供了”$default”值,就会返回。会被返回。如果没有,将返回布尔值`false`。
2. 当使用选项API过滤器之一时。{@see ‘pre_option_$option’}, {@see ‘default_option_$option’}, or {@see ‘option_$option’}, the return 值可能不符合预期的类型。
3. 当选项刚刚被保存在数据库中,并且get_option() 之后,非字符串的标量值和空值不会被转换为等同于字符串的值。字符串等价物,并返回原始类型。

示例:

当像这样添加选项时。`add_option( ‘my_option_name’, ‘value’)`这样添加选项时。然后用`get_option( ‘my_option_name’)`来获取它们,返回的 返回的值将是:

– `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)””`

当添加非标量值的选项时,如 `add_option( ‘my_array’, array( false, ‘str’, null )`, 返回值 将与原始值相同,因为它在保存到数据库之前被序列化了 它被序列化后保存在数据库中:

array(3) {
[0] => bool(false)
[1] => string(3)”str”
[2] => NULL
}

function get_option( $option, $default = 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 );
	}

	/**
	 * 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` parameter was added.
	 *
	 * @param mixed  $pre_option The value to return instead of the option value. This differs
	 *                           from `$default`, 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    The fallback value to return if the option does not exist.
	 *                           Default false.
	 */
	$pre = apply_filters( "pre_option_{$option}", false, $option, $default );

	/**
	 * 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`, 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     The fallback value to return if the option does not exist.
	 *                            Default false.
	 */
	$pre = apply_filters( 'pre_option', $pre, $option, $default );

	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() ) {
		// Prevent non-existent options from triggering multiple queries.
		$notoptions = wp_cache_get( 'notoptions', 'options' );

		// Prevent non-existent `notoptions` key from triggering multiple key lookups.
		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 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, $option, $passed_default );
		}

		$alloptions = wp_load_alloptions();

		if ( isset( $alloptions[ $option ] ) ) {
			$value = $alloptions[ $option ];
		} else {
			$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.
					if ( ! is_array( $notoptions ) ) {
						$notoptions = array();
					}

					$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, $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, $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 );
}

常见问题

FAQs
查看更多 >