函数文档

wp_set_post_terms()

💡 云策文档标注

概述

wp_set_post_terms() 函数用于为文章设置术语(如标签或分类),是 WordPress 中处理文章与术语关联的核心函数。它封装了 wp_set_object_terms(),提供便捷接口,支持参数控制术语的添加或替换。

关键要点

  • 函数作用:设置文章的术语,可应用于标签、分类等自定义分类法。
  • 参数说明:$post_id(文章 ID,默认为 0,不默认使用全局 $post)、$terms(术语数组或逗号分隔字符串,默认为空)、$taxonomy(分类法名称,默认为 'post_tag')、$append(布尔值,true 表示追加术语,false 表示替换术语,默认为 false)。
  • 返回值:成功时返回受影响术语的术语分类 ID 数组,失败时返回 false 或 WP_Error。
  • 注意事项:对于分层分类法(如分类),必须传递术语 ID 而非名称,以避免同名子项混淆;非分层分类法(如标签)可传递名称或 ID,但传递 ID 时需确保为整数并放入数组。
  • 相关函数:内部调用 wp_set_object_terms(),适用于原生文章类型;自定义文章类型应直接使用 wp_set_object_terms()。

代码示例

// 非分层术语示例(如标签)
$tag = array( 5 ); // 正确:传递 ID 为整数的数组
wp_set_post_terms( $post_id, $tag, $taxonomy );

// 分层术语示例(如分类)
$term_id = term_exists( $term, $taxonomy, $parent ); // 获取术语 ID
wp_set_post_terms( $post_id, $term_id, $taxonomy ); // 传递 ID

注意事项

  • 传递术语 ID 时,必须确保为整数类型并放入数组,否则可能被误解释为术语名称。
  • 函数仅适用于原生文章类型,自定义文章类型需使用 wp_set_object_terms()。
  • 参数 $append 控制术语操作方式:true 为追加,false 为替换,默认 false。

📄 原文内容

Sets the terms for a post.

Description

See also

Parameters

$post_idintoptional
The Post ID. Does not default to the ID of the global $post.
$termsstring|arrayoptional
An array of terms to set for the post, or a string of terms separated by commas. Hierarchical taxonomies must always pass IDs rather than names so that children with the same names but different parents aren’t confused. Default empty.
$taxonomystringoptional
Taxonomy name. Default 'post_tag'.
$appendbooloptional
If true, don’t delete existing terms, just add on. If false, replace the terms with the new terms.

Default:false

Return

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

Source

function wp_set_post_terms( $post_id = 0, $terms = '', $taxonomy = 'post_tag', $append = false ) {
	$post_id = (int) $post_id;

	if ( ! $post_id ) {
		return false;
	}

	if ( empty( $terms ) ) {
		$terms = array();
	}

	if ( ! is_array( $terms ) ) {
		$comma = _x( ',', 'tag delimiter' );
		if ( ',' !== $comma ) {
			$terms = str_replace( $comma, ',', $terms );
		}
		$terms = explode( ',', trim( $terms, " ntrx0B," ) );
	}

	/*
	 * Hierarchical taxonomies must always pass IDs rather than names so that
	 * children with the same names but different parents aren't confused.
	 */
	if ( is_taxonomy_hierarchical( $taxonomy ) ) {
		$terms = array_unique( array_map( 'intval', $terms ) );
	}

	return wp_set_object_terms( $post_id, $terms, $taxonomy, $append );
}

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Non hierarchical term example

    For non-hierarchical terms (such as tags), you can pass either the term name or id. If you pass the id there is only one caveat: You must pass it as an integer, and it must be in an array. This is necessary because any non-array value passed will be converted to a string, which will be interpreted as a term name.

    $tag = '5'; // Wrong. This will add the tag with the *name* '5'.
    $tag = 5; // Wrong. This will also add the tag with the name '5'.
    $tag = array( '5' ); // Wrong. Again, this will be interpreted as a term name rather than an id.
    
    $tag = array( 5 ); // Correct. This will add the tag with the id 5.
    wp_set_post_terms( $post_id, $tag, $taxonomy );

    This function will only work on the native post type. For a taxonomy on a custom post type use wp_set_object_terms()

  2. Skip to note 5 content

    I do not know why, but you need to wrap your term_id in Array ((int) $ Term_id) – Then it will work as id … otherwise it is to create a term with name = $ Term_id

    $exchange = term_exists( $this->response['exchangeShortName'], 'exchange' );
    
    if ( ! $exchange ) {
        $exchange = wp_insert_term( $this->response['exchange'], 'exchange', array( 'slug' => $this->response['exchangeShortName'] ) );
    }
    
    // create new term with name = $exchange['term_id'] - BUG?
    wp_set_post_terms( $this->postID, array( $exchange['term_id'] ), 'exchange', false ); 
    
    // It works fine, does not create a new term, and simply attaches the existing ID
    wp_set_post_terms( $this->postID, array( (int) $exchange['term_id'] ), 'exchange', false );

  3. Skip to note 6 content

    Hierarchical term example

    For hierarchical terms (such as categories), you must always pass the id rather than the term name to avoid confusion where there may be another child with the same name.

    To get the term id you can use:

    $term_id = term_exists( $term, $taxonomy, $parent );

    You may also need to pass by reference:

    wp_set_post_terms( $post_id, $term, &$taxonomy );