如何防止wp_insert_post()设置Uncategorized类别?

Giu*_*ius 0 wordpress post insert

我正在使用Wordpress 3.5,似乎wp_insert_post()无法再设置类别,文档系统:

post_category不再存在,请尝试wp_set_post_terms()来设置帖子的类别

问题是wp_set_post_terms()wp_set_object_terms()要求postID,返回wp_insert_post().虽然可以将类别术语设置为插入的帖子wp_insert_post(),但问题是我每次打电话时wp_insert_post()都会Uncategorized在帖子中获取类别,此外还有我在调用后设置的类别术语wp_insert_post().我怎样才能阻止Uncategorized它永远存在?

The*_*pha 5

我不知道你在哪里找到了,wp_insert_post() can't set categories anymore但是从WordPress Doc你可以做到这一点

// Create post object
$my_post = array(
    'post_title'    => 'My post',
    'post_content'  => 'This is my post.',
    'post_status'   => 'publish',
    'post_author'   => 1,
    'post_category' => array(8,39) // id's of categories
);

// Insert the post into the database
wp_insert_post( $my_post );
Run Code Online (Sandbox Code Playgroud)

Bellow是我的一个工作示例,我正在我的网站中使用一个管理员动态添加新帖子,类别名称location包含两个元字段,输入来自用户(我已经过滤了用户输入,但在此处省略)

$category='location'; // category name for the post
$cat_ID = get_cat_ID( $category ); // need the id of 'location' category
//If it doesn't exist create new 'location' category
if($cat_ID == 0) {
    $cat_name = array('cat_name' => $category);
    wp_insert_category($cat_name); // add new category
}
//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);
$my_post = array(
    'post_title' => $_POST['location_name'],
    'post_content' => $_POST['location_content'],
    'post_status' => 'publish',
    'post_author' => 1,
    'post_category' => array($new_cat_ID)
);
// Insert a new post
$newpost_id=wp_insert_post($my_post);
// if post has been inserted then add post meta 
if($newpost_id!=0)
{
    // I've checked whether the email and phone fields are empty or not
    // add  both meta
    add_post_meta($newpost_id, 'email', $_POST['email']);
    add_post_meta($newpost_id, 'phone', $_POST['phone']);
}
Run Code Online (Sandbox Code Playgroud)

还要记住,每次添加没有类别的新帖子时,都会WordPress设置该帖子的默认类别,uncategorized如果您没有从管理面板更改它,则可以将默认类别更改为uncategorized您想要的任何内容.

更新:

由于post_category不存在,所以你可以更换

'post_category' => array($new_cat_ID)
Run Code Online (Sandbox Code Playgroud)

以下

'tax_input' => array( 'category' => $new_cat_ID )
Run Code Online (Sandbox Code Playgroud)

在上面给出的例子中.你也可以使用

$newpost_id=wp_insert_post($my_post);
wp_set_post_terms( $newpost_id, array($new_cat_ID), 'category' );
Run Code Online (Sandbox Code Playgroud)

请记住,在此示例中,$new_cat_ID已使用以下代码行找到了该代码

$new_cat_ID = get_cat_ID($category);
Run Code Online (Sandbox Code Playgroud)

但也可以使用以下代码获取类别ID

$category_name='location';
$term=get_term_by('name', $category_name, 'category');
$cat_ID = $term->term_id;
Run Code Online (Sandbox Code Playgroud)

阅读有关get_term_by函数的更多信息.