Wordpress - 以编程方式插入新类别的帖子?

时间:2010-11-25 13:35:29

标签: wordpress

我编写了一个脚本,它接受一些新闻的XML提要,并使用wp_insert_post()将每个新闻故事作为帖子插入到WordPress中。

这些新闻报道中的每一个都有一个我想要添加到WordPress的类别。

我的问题是,我如何动态创建新类别并使用wp_insert_post()(或任何其他函数)将帖子分配给该类别?

谢谢!

2 个答案:

答案 0 :(得分:3)

我最后通过编写以下代码对其进行了排序:

//Check if category already exists
$cat_ID = get_cat_ID( $category );

//If it doesn't exist create new category
if($cat_ID == 0) {
    $cat_name = array('cat_name' => $category);
    wp_insert_category($cat_name);
}

//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);

// Create post object
$new_post = array(
    'post_title' => $headline,
    'post_content' => $body,
    'post_excerpt' => $excerpt,
    'post_date' => $date,
    'post_date_gmt' => $date,
    'post_status' => 'publish',
    'post_author' => 1,
    'post_category' => array($new_cat_ID)
);

// Insert the post into the database
wp_insert_post( $new_post );

答案 1 :(得分:1)

试试这个:

$my_cat = array('cat_name' => 'My Category', 'category_description' => 'A Cool Category', 'category_nicename' => 'category-slug', 'category_parent' => '');

$my_cat_id = wp_insert_category($my_cat);

$my_post = array(
   'post_title' => 'My post',
   'post_content' => 'This is my post.',
   'post_status' => 'publish',
   'post_author' => 1,
   'post_category' => array($my_cat_id)
);

wp_insert_post( $my_post );
  

警告:未经测试。这一切都被采取了   来自wp_insert_post()和   wp_insert_category()页面上   抄本。

相关问题