返回介绍

update_option()

发布于 2017-09-11 11:05:10 字数 15794 浏览 1043 评论 0 收藏 0

update_option( string $option,  mixed $value,  string|bool $autoload = null )

Update the value of an option that was already added.


description

You do not need to serialize values. If the value needs to be serialized, then it will be serialized before it is inserted into the database. Remember, re源代码s can not be serialized or added as an option.

If the option does not exist, then the option will be added with the option value, with an $autoload value of ‘yes’.


参数

$option

(string) (Required) Option name. Expected to not be SQL-escaped.

$value

(mixed) (Required) Option value. Must be serializable if non-scalar. Expected to not be SQL-escaped.

$autoload

(string|bool) (Optional) Whether to load the option when WordPress starts up. For existing options, $autoload can only be updated using update_option() if $value is also changed. Accepts 'yes'|true to enable or 'no'|false to disable. For non-existent options, the default value is 'yes'.

Default value: null


返回值

(bool) False if value was not updated and true if value was updated.


源代码

File: wp-includes/option.php

function update_option( $option, $value, $autoload = null ) {
	global $wpdb;

	$option = trim($option);
	if ( empty($option) )
		return false;

	wp_protect_special_option( $option );

	if ( is_object( $value ) )
		$value = clone $value;

	$value = sanitize_option( $option, $value );
	$old_value = get_option( $option );

	/**
	 * Filters a specific option before its value is (maybe) serialized and updated.
	 *
	 * The dynamic portion of the hook name, `$option`, refers to the option name.
	 *
	 * @since 2.6.0
	 * @since 4.4.0 The `$option` parameter was added.
	 *
	 * @param mixed  $value     The new, unserialized option value.
	 * @param mixed  $old_value The old option value.
	 * @param string $option    Option name.
	 */
	$value = apply_filters( "pre_update_option_{$option}", $value, $old_value, $option );

	/**
	 * Filters an option before its value is (maybe) serialized and updated.
	 *
	 * @since 3.9.0
	 *
	 * @param mixed  $value     The new, unserialized option value.
	 * @param string $option    Name of the option.
	 * @param mixed  $old_value The old option value.
	 */
	$value = apply_filters( 'pre_update_option', $value, $option, $old_value );

	/*
	 * If the new and old values are the same, no need to update.
	 *
	 * Unserialized values will be adequate in most cases. If the unserialized
	 * data differs, the (maybe) serialized data is checked to avoid
	 * unnecessary database calls for otherwise identical object instances.
	 *
	 * See https://core.trac.wordpress.org/ticket/38903
	 */
	if ( $value === $old_value || maybe_serialize( $value ) === maybe_serialize( $old_value ) ) {
		return false;
	}

	/** This filter is documented in wp-includes/option.php */
	if ( apply_filters( "default_option_{$option}", false, $option, false ) === $old_value ) {
		// Default setting for new options is 'yes'.
		if ( null === $autoload ) {
			$autoload = 'yes';
		}

		return add_option( $option, $value, '', $autoload );
	}

	$serialized_value = maybe_serialize( $value );

	/**
	 * Fires immediately before an option value is updated.
	 *
	 * @since 2.9.0
	 *
	 * @param string $option    Name of the option to update.
	 * @param mixed  $old_value The old option value.
	 * @param mixed  $value     The new option value.
	 */
	do_action( 'update_option', $option, $old_value, $value );

	$update_args = array(
		'option_value' => $serialized_value,
	);

	if ( null !== $autoload ) {
		$update_args['autoload'] = ( 'no' === $autoload || false === $autoload ) ? 'no' : 'yes';
	}

	$result = $wpdb->update( $wpdb->options, $update_args, array( 'option_name' => $option ) );
	if ( ! $result )
		return false;

	$notoptions = wp_cache_get( 'notoptions', 'options' );
	if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
		unset( $notoptions[$option] );
		wp_cache_set( 'notoptions', $notoptions, 'options' );
	}

	if ( ! wp_installing() ) {
		$alloptions = wp_load_alloptions();
		if ( isset( $alloptions[$option] ) ) {
			$alloptions[ $option ] = $serialized_value;
			wp_cache_set( 'alloptions', $alloptions, 'options' );
		} else {
			wp_cache_set( $option, $serialized_value, 'options' );
		}
	}

	/**
	 * Fires after the value of a specific option has been successfully updated.
	 *
	 * The dynamic portion of the hook name, `$option`, refers to the option name.
	 *
	 * @since 2.0.1
	 * @since 4.4.0 The `$option` parameter was added.
	 *
	 * @param mixed  $old_value The old option value.
	 * @param mixed  $value     The new option value.
	 * @param string $option    Option name.
	 */
	do_action( "update_option_{$option}", $old_value, $value, $option );

	/**
	 * Fires after the value of an option has been successfully updated.
	 *
	 * @since 2.9.0
	 *
	 * @param string $option    Name of the updated option.
	 * @param mixed  $old_value The old option value.
	 * @param mixed  $value     The new option value.
	 */
	do_action( 'updated_option', $option, $old_value, $value );
	return true;
}

更新日志

Versiondescription
4.2.0The $autoload parameter was added.
1.0.0Introduced.

相关函数

Uses

  • wp-includes/load.php: wp_installing()
  • wp-includes/cache.php: wp_cache_get()
  • wp-includes/cache.php: wp_cache_set()
  • wp-includes/formatting.php: sanitize_option()
  • wp-includes/functions.php: maybe_serialize()
  • wp-includes/plugin.php: apply_filters()
  • wp-includes/plugin.php: do_action()
  • wp-includes/option.php: add_option()
  • wp-includes/option.php: wp_load_alloptions()
  • wp-includes/option.php: pre_update_option_{$option}
  • wp-includes/option.php: pre_update_option
  • wp-includes/option.php: update_option
  • wp-includes/option.php: update_option_{$option}
  • wp-includes/option.php: updated_option
  • wp-includes/option.php: wp_protect_special_option()
  • wp-includes/option.php: get_option()
  • wp-includes/option.php: default_option_{$option}
  • wp-includes/wp-db.php: wpdb::update()
  • Show 13 more uses Hide more uses

Used By

  • wp-includes/class-wp-customize-manager.php: WP_Customize_Manager::update_stashed_theme_mod_settings()
  • wp-includes/class-wp-customize-manager.php: WP_Customize_Manager::save_changeset_post()
  • wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php: WP_REST_Settings_Controller::update_item()
  • wp-includes/functions.php: _delete_option_fresh_site()
  • wp-admin/includes/class-wp-upgrader.php: WP_Upgrader::create_lock()
  • wp-includes/class-wp-customize-setting.php: WP_Customize_Setting::set_root_value()
  • wp-includes/option.php: update_network_option()
  • wp-admin/includes/ajax-actions.php: wp_ajax_delete_inactive_widgets()
  • wp-includes/customize/class-wp-customize-nav-menu-setting.php: WP_Customize_Nav_Menu_Setting::update()
  • wp-includes/taxonomy.php: _wp_batch_split_terms()
  • wp-admin/includes/class-wp-plugins-list-table.php: WP_Plugins_List_Table::prepare_items()
  • wp-admin/includes/ms.php: update_option_new_admin_email()
  • wp-admin/includes/misc.php: update_recently_edited()
  • wp-admin/includes/schema.php: populate_options()
  • wp-admin/includes/dashboard.php: wp_dashboard_rss_control()
  • wp-admin/includes/upgrade.php: make_site_theme()
  • wp-admin/includes/upgrade.php: maybe_disable_automattic_widgets()
  • wp-admin/includes/upgrade.php: maybe_disable_link_manager()
  • wp-admin/includes/upgrade.php: wp_install()
  • wp-admin/includes/upgrade.php: wp_install_defaults()
  • wp-admin/includes/plugin.php: uninstall_plugin()
  • wp-admin/includes/plugin.php: activate_plugin()
  • wp-admin/includes/plugin.php: deactivate_plugins()
  • wp-admin/includes/plugin.php: validate_active_plugins()
  • wp-admin/includes/nav-menu.php: wp_nav_menu_update_menu_items()
  • wp-admin/includes/file.php: request_filesystem_credentials()
  • wp-includes/class-wp-roles.php: WP_Roles::add_cap()
  • wp-includes/class-wp-roles.php: WP_Roles::remove_cap()
  • wp-includes/class-wp-roles.php: WP_Roles::add_role()
  • wp-includes/class-wp-roles.php: WP_Roles::remove_role()
  • wp-includes/cron.php: _set_cron_array()
  • wp-includes/cron.php: _upgrade_cron_array()
  • wp-includes/theme.php: check_theme_switched()
  • wp-includes/theme.php: set_theme_mod()
  • wp-includes/theme.php: remove_theme_mod()
  • wp-includes/theme.php: switch_theme()
  • wp-includes/theme.php: get_theme_mods()
  • wp-includes/class-wp-theme.php: WP_Theme::get_allowed_on_site()
  • wp-includes/plugin.php: register_uninstall_hook()
  • wp-includes/option.php: set_transient()
  • wp-includes/post.php: _reset_front_page_settings_for_post()
  • wp-includes/post.php: stick_post()
  • wp-includes/post.php: unstick_post()
  • wp-includes/class-wp-rewrite.php: WP_Rewrite::set_permalink_structure()
  • wp-includes/class-wp-rewrite.php: WP_Rewrite::set_category_base()
  • wp-includes/class-wp-rewrite.php: WP_Rewrite::set_tag_base()
  • wp-includes/class-wp-rewrite.php: WP_Rewrite::wp_rewrite_rules()
  • wp-includes/class-wp-rewrite.php: WP_Rewrite::flush_rules()
  • wp-includes/revision.php: _wp_upgrade_revisions_of_post()
  • wp-includes/ms-functions.php: update_posts_count()
  • wp-includes/ms-functions.php: global_terms()
  • wp-includes/ms-functions.php: wpmu_create_blog()
  • wp-includes/ms-functions.php: install_blog()
  • wp-includes/ms-blogs.php: update_blog_details()
  • wp-includes/ms-blogs.php: update_blog_option()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::wp_setOptions()
  • wp-includes/class-wp-widget.php: WP_Widget::save_settings()
  • wp-includes/widgets.php: wp_set_sidebars_widgets()
  • wp-includes/widgets.php: wp_convert_widget_settings()
  • Show 54 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 1You must log in to vote on the helpfulness of this note Contributed by bellasys

    According to the WordPress Codex (and my experiences developing with WP) note an important subtlety in the return value here:
    “True if option value has changed, false if not or if update failed.

    It is also recommended on some forums to check for the existence of an option via code:

    if ( ! get_option('my_option') ) ...

    But I don’t find this works when the option exists and I have set my_option to bool FALSE!

    To handle all checking of existence of options, I exploit the update_option subtlety:

    if (FALSE === get_option('my_option') && FALSE === update_option('my_option',FALSE)) add_option('my_option',$default_value);

    The second check yields FALSE when setting the option with the value of FALSE produces no change…therefore if the value truly didn’t exist, it will be added with (in my case) the desired $default_value.

    I know this seems extreme, but to the best of my knowledge this is the only way I’ve been able to preserve bool FALSE on my plugin options, and to assert valid actions based on the actual presence of my custom options.

  2. Usage

    <?php update_option( $option, $new_value, $autoload ); ?>

    Example: Updating Core Options
    Set the default comment status to ‘closed’:

    <?php update_option( 'default_comment_status', 'closed' ); ?>

    This option is usually set in from the Settings > Discussion administration panel. See the Option Reference for a full list of options used by WordPress Core.

    Note: Use get_option() to confirm an option value.

    <?php echo get_option( 'default_comment_status' ); ?>

    Example: Updating Custom Options
    You can also create your own custom options. This example updates the option 'my_custom_option' with the value 255:

    <?php update_option( 'my_custom_option', 255 ); ?>

    This will automatically add the option if it does not exist (and set the option’s value).

    If you don’t want your custom option to auto-load when WordPress starts up, use add_option(). This example updates the option if it already exists; if it does not exist it uses add_option() to set $autoload to 'no'.

    <?php
    $option_name = 'my_custom_color_option' ;
    $new_value = 'red';
    
    if ( get_option( $option_name ) !== false ) {
    
        // The option already exists, so update it.
        update_option( $option_name, $new_value );
    
    } else {
    
        // The option hasn't been created yet, so add it with $autoload set to 'no'.
        $deprecated = null;
        $autoload = 'no';
        add_option( $option_name, $new_value, $deprecated, $autoload );
    }
    ?>

    Note
    Option values retrieved via WordPress functions are cached. If you modify an options outside of the Options API, then try to update a cached option, the update will fail and return false. Use the following method to clear the options cache before trying to get or update the options on the same request:

    <?php wp_cache_delete ( 'alloptions', 'options' ); ?>

    Use wp_load_alloptions() to print a list of all options:

    <?php 
    $alloptions  = wp_load_alloptions();
    var_dump( $alloptions );
    ?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文