【发布时间】:2013-07-06 12:53:15
【问题描述】:
我正在构建一个 WordPress 主题,人们可以在其中使用 wp_insert_post 提交帖子。下面的代码添加了帖子标题,但没有添加用户指定的类别。相反,它将它放在uncategorized 中。
如何在提交时将新类别添加到帖子中?
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$new_cat_ID = $_POST['category'];
//Checking if category already there
$cat_ID = get_cat_ID( $_POST['newcat'] );
//If not create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $_POST['newcat']);
wp_insert_category($cat_name);
}
//Get ID of newly created category
$new_cat_ID = get_cat_ID($_POST['newcat']);
// Create post object
$new_post = array(
'ID' => '',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user->ID,
'tax_input' => array( 'category' => $new_cat_ID )
);
// Insert the post into the database
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( home_url() );
exit;
}
这是表单的 HTML:
<form style="" action="" method="post" id="foo">
<input type="hidden" name="new_post" value="1"/>
<input type="text" name="post_title" value="title" id="input-title"/>
<input type="text" name="category" value="apples" id="category" />
<input type="submit" value="Login">
</form>
【问题讨论】:
-
您的
inputname是category,但您正在检查$_POST['newcat']。阅读Data Validation 以确保您的代码安全。您还需要this。 -
谢谢!我了解类别部分,但我仍然不确定将 wp_insert_term 放在哪里。你介意修改我的代码给我看吗?
标签: wordpress forms post insert frontend