函数文档

add_blog_option()

💡 云策文档标注

概述

add_blog_option() 函数用于为指定博客 ID 添加新选项,适用于 WordPress 多站点环境。它处理选项的添加,包括序列化检查和保护选项验证。

关键要点

  • 函数用于为给定博客 ID 添加新选项,支持多站点操作。
  • 参数包括博客 ID(可为 null 表示当前博客)、选项名称和值,均无需 SQL 转义。
  • 返回值是布尔值:成功添加返回 true,否则返回 false。
  • 注意事项:值会自动序列化(如需要),但资源类型不能序列化;避免使用受保护的 WordPress 选项名称。

代码示例

// 为多站点添加选项的示例函数
function wpdocs_MWBOption( $name, $value, $blogID ) {
     if ( is_multisite() ) {
         return add_blog_option( $blogID, $name, $value );
     }
     return add_option( $name, $value );
}

📄 原文内容

Adds a new option for a given blog ID.

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, resources can not be serialized or added as an option.

You can create options without values and then update the values later.
Existing options will not be updated and checks are performed to ensure that you aren’t adding a protected WordPress option. Care should be taken to not name options the same as the ones which are protected.

Parameters

$idintrequired
A blog ID. Can be null to refer to the current blog.
$optionstringrequired
Name of option to add. Expected to not be SQL-escaped.
$valuemixedrequired
Option value, can be anything. Expected to not be SQL-escaped.

Return

bool True if the option was added, false otherwise.

Source

function add_blog_option( $id, $option, $value ) {
	$id = (int) $id;

	if ( empty( $id ) ) {
		$id = get_current_blog_id();
	}

	if ( get_current_blog_id() === $id ) {
		return add_option( $option, $value );
	}

	switch_to_blog( $id );
	$return = add_option( $option, $value );
	restore_current_blog();

	return $return;
}

Changelog

Version Description
MU (3.0.0) Introduced.

User Contributed Notes