开发者

Wordpress - Programmatically inserting posts with NEW categories?

开发者 https://www.devze.com 2023-01-27 10:42 出处:网络
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().

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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消