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
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. |
Skip to note 3 content
Niamul Islam
Add
arrayof tags to post with ID 100, if a tag already exist, it will replace the existing one.$post_id = 100; // ID of Post $tags = array('Mango', 'Apple', 'Banana'); // Array of Tags to add wp_set_post_tags( $post_id, $tags); // Set tags to PostSkip to note 4 content
Codex
To add the tags meaning and life in addition to the current tags of the post with ID 42:
wp_set_post_tags( 42, 'meaning,life', true );