我试图插入类别
$apples = "granny smith"
作为新帖子的一部分。
我可以使用以下脚本轻松创建带有TAG的新帖子:
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'tags_input' => $apples,
'post_type' => 'post'
);
wp_insert_post( $my_post );
但出于某种原因,尽管WP编码列表
'post_category'
对于类别,以下代码不会创建新类别“granny smith”,而是以“未分类”的形式输入新帖子:
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $apples
'post_type' => 'post'
);
wp_insert_post( $my_post );
有人可以帮我解决问题吗?我哪里错了?
答案 0 :(得分:0)
根据the documentation,类别应该添加为类别为id的数组:
$id_for_category_ganny_smith = 12;
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array($id_for_category_ganny_smith),
'post_type' => 'post'
);
wp_insert_post( $my_post );
文档说明:
类别需要作为匹配的整数数组传递 数据库中的类别ID。即使只有一个也是如此 类别已分配到帖子。
如果您不知道要添加的类别的ID,可以尝试以下操作:
$apples_slug = "granny_smith"
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post'
);
$post_ID = wp_insert_post( $my_post );
wp_set_post_terms( $post_ID, $apples_slug, 'category')