函数文档

update_user_option()

💡 云策文档标注

概述

update_user_option() 函数用于更新用户选项,支持全局博客选项功能。它基于用户 ID 和选项名称操作,可处理博客特定或全局选项,并在新值为空时删除选项。

关键要点

  • 函数更新用户选项,类似于用户元数据,但支持全局博客选项。
  • 参数 $is_global 控制选项是否为全局:默认 false(博客特定),会添加 WordPress 表前缀到选项名。
  • 如果 $newvalue 为空,函数会删除用户选项。
  • 返回值:选项不存在时返回用户元 ID,成功更新返回 true,失败返回 false。
  • 内部调用 update_user_meta() 实现功能。

代码示例

// 隐藏前端管理员栏
update_user_option( $user_id, 'show_admin_bar_front', false );

// 在多站点中设置全局选项
update_user_option( $user_id, 'show_admin_bar_front', false, true );

📄 原文内容

Updates user option with global blog capability.

Description

User options are just like user metadata except that they have support for global blog options. If the ‘is_global’ parameter is false, which it is by default, it will prepend the WordPress table prefix to the option name.

Deletes the user option if $newvalue is empty.

Parameters

$user_idintrequired
User ID.
$option_namestringrequired
User option name.
$newvaluemixedrequired
User option value.
$is_globalbooloptional
Whether option name is global or blog specific.
Default false (blog specific).

Default:false

Return

int|bool User meta ID if the option didn’t exist, true on successful update, false on failure.

Source

function update_user_option( $user_id, $option_name, $newvalue, $is_global = false ) {
	global $wpdb;

	if ( ! $is_global ) {
		$option_name = $wpdb->get_blog_prefix() . $option_name;
	}

	return update_user_meta( $user_id, $option_name, $newvalue );
}

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Basic Example

    Hide the admin bar for a user on the front end of the site:

    update_user_option( $user_id, 'show_admin_bar_front', false );

    When multisite is installed, the $global parameter can be used to set the user option for the whole network, instead of just the current site:

    update_user_option( $user_id, 'show_admin_bar_front', false, true );