WordPress函数wp_set_post_terms()通过代码设置文章的分类

描述:

通过代码设置文章的分类

用法:

<?php wp_set_post_terms( $post_id, $terms, $taxonomy, $append ) ?>

参数:

$post_id

(integer) (必填) 文章ID.

默认值: 0

$terms

(string,array) (可选) 分类列表。可以是数组或逗号分隔的字符串。如果要输入与类别类似的层次分类法的术语,请使用id。如果要添加非层次术语(如标记),请使用名称。

默认值: array

$taxonomy

(string) (可选) 可能的值,例如:“category”、“post_tag”、“taxonomy slug”

默认值: post_tag

$append

(boolean) (可选) 如果为true,则标记将附加到帖子中。如果为false,标签将替换现有的标签。

默认值: false

源文件:

/**
 * Set the terms for a post.
 *
 * @since 2.8.0
 *
 * @see wp_set_object_terms()
 *
 * @param int    $post_id  Optional. The Post ID. Does not default to the ID of the global $post.
 * @param string $tags     Optional. The tags to set for the post, separated by commas. Default empty.
 * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
 * @param bool   $append   Optional. 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 affected term IDs. WP_Error or false on failure.
 */
function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
	$post_id = (int) $post_id;

	if ( !$post_id )
		return false;

	if ( empty($tags) )
		$tags = array();

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

	/*
	 * 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 ) ) {
		$tags = array_unique( array_map( 'intval', $tags ) );
	}

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

 

分享到:
赞(0)

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址