函数文档

wp_create_categories()

💡 云策文档标注

概述

wp_create_categories() 函数用于为指定文章创建分类。它接受分类名称数组和可选的文章ID,返回分配给文章的分类ID数组。

关键要点

  • 参数:$categories(必需,字符串数组,要创建的分类名称),$post_id(可选,整数,文章ID,默认为0)。
  • 返回值:整数数组,分配给给定文章的分类ID。
  • 功能:遍历分类名称数组,使用category_exists()检查分类是否存在,若存在则记录ID,否则使用wp_create_category()创建新分类并记录ID;如果提供了$post_id,则调用wp_set_post_categories()为文章设置分类。

代码示例

function wp_create_categories( $categories, $post_id = 0 ) {
    $cat_ids = array();
    foreach ( $categories as $category ) {
        $id = category_exists( $category );
        if ( $id ) {
            $cat_ids[] = $id;
        } else {
            $id = wp_create_category( $category );
            if ( $id ) {
                $cat_ids[] = $id;
            }
        }
    }

    if ( $post_id ) {
        wp_set_post_categories( $post_id, $cat_ids );
    }

    return $cat_ids;
}

注意事项

  • 相关函数:category_exists()、wp_create_category()、wp_set_post_categories()。
  • 版本历史:自WordPress 2.0.0引入。

📄 原文内容

Creates categories for the given post.

Parameters

$categoriesstring[]required
Array of category names to create.
$post_idintoptional
The post ID. Default empty.

Return

int[] Array of IDs of categories assigned to the given post.

Source

function wp_create_categories( $categories, $post_id = 0 ) {
	$cat_ids = array();
	foreach ( $categories as $category ) {
		$id = category_exists( $category );
		if ( $id ) {
			$cat_ids[] = $id;
		} else {
			$id = wp_create_category( $category );
			if ( $id ) {
				$cat_ids[] = $id;
			}
		}
	}

	if ( $post_id ) {
		wp_set_post_categories( $post_id, $cat_ids );
	}

	return $cat_ids;
}

Changelog

Version Description
2.0.0 Introduced.