Wordpress - Programmatically inserting posts with

2020-08-04 04:35发布

I have written a script that takes an XML feed of some news, and inserts each news story as a post into WordPress using wp_insert_post().

Each of these news stories has a category that I would like to add to WordPress also.

My question is, how can I create NEW categories on the fly and assign the post to that category using wp_insert_post() (or any other function)?

Thanks!

标签: wordpress
2条回答
啃猪蹄的小仙女
2楼-- · 2020-08-04 05:09

I sorted it in the end by writing the following code:

//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 );
查看更多
Evening l夕情丶
3楼-- · 2020-08-04 05:23

Try this:

$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 );

Warning: Untested. It was all taken from wp_insert_post() and wp_insert_category() page on codex.

查看更多
登录 后发表回答