函数文档

wp_set_post_tags()

💡 云策文档标注

概述

wp_set_post_tags() 函数用于为文章设置标签,基于 wp_set_post_terms() 实现,支持通过数组或逗号分隔字符串指定标签,并可选择追加或替换现有标签。

关键要点

  • 函数参数包括 $post_id(文章ID,可选,默认0)、$tags(标签数组或字符串,可选,默认空)和 $append(布尔值,可选,默认false,控制是否追加标签)。
  • 返回值为受影响术语的分类法ID数组,失败时返回 false 或 WP_Error。
  • 标签可以混合使用文本和现有标签ID:文本会自动创建新标签(如果不存在),ID则引用现有标签。
  • 此函数是 wp_set_post_terms() 的包装器,专门用于 post_tag 分类法。

代码示例

// 示例1:为ID为100的文章设置标签数组,替换现有标签
$post_id = 100;
$tags = array('Mango', 'Apple', 'Banana');
wp_set_post_tags($post_id, $tags);

// 示例2:为ID为42的文章追加标签字符串,保留现有标签
wp_set_post_tags(42, 'meaning,life', true);

📄 原文内容

Sets the tags for a post.

Description

See also

Parameters

$post_idintoptional
The Post ID. Does not default to the ID of the global $post.
$tagsstring|arrayoptional
An array of tags to set for the post, or a string of tags separated by commas. Default empty.
$appendbooloptional
If true, don’t delete existing tags, just add on. If false, replace the tags with the new tags.

Default:false

Return

array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.

More Information

If you set IDs of an existing tag in the array, WordPress assigns the existing tag.

If you pass text in the array, WP will create a tag if it doesn’t exist and assigns it to the post

You can mix text and IDs. The text will create a term, if it not exists, the ID will be used for an existing tag – both get assigned to the post.

Source

function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
	return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes