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

时间:2012-12-25 20:23:05

标签: wordpress post insert

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

  

post_category不再存在,请尝试使用wp_set_post_terms()进行设置   帖子的类别

问题是wp_set_post_terms()wp_set_object_terms()需要postIDwp_insert_post()会返回wp_insert_post()。虽然可以将类别字词设置为wp_insert_post()插入的帖子,但问题是我每次拨打Uncategorized时都会在帖子中获得wp_insert_post()类别,此外还有类别我在致电Uncategorized后设定的条款。如何阻止{{1}}始终在那里?

1 个答案:

答案 0 :(得分: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 );

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

$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']);
}

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

更新

由于post_category不再存在,因此您可以替换

'post_category' => array($new_cat_ID)

以下

'tax_input' => array( 'category' => $new_cat_ID )

在上面给出的例子中。您也可以使用

$newpost_id=wp_insert_post($my_post);
wp_set_post_terms( $newpost_id, array($new_cat_ID), 'category' );

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

$new_cat_ID = get_cat_ID($category);

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

$category_name='location';
$term=get_term_by('name', $category_name, 'category');
$cat_ID = $term->term_id;

详细了解get_term_by功能。