我无法让它工作。我有一个页面,用户可以在其中提交他们的帖子。在那里,理想情况下我想显示所有类别并让他们通过下拉列表选择类别以分配帖子。我无法解决这个问题,因为我是 PHP 方面的新手,所以我决定逐步进行,首先从添加一个空输入字段开始,用户可以在其中添加一个随机文本,该文本将成为该帖子的类别。
为此,我做了以下工作:
if(isset($_POST['entry']) AND !$_POST['entry'] == ""):
$my_post = array();
$my_post['post_title'] = $_POST['title'];
$my_post['post_content'] = $_POST['entry'];
$my_post['post_status'] = 'publish';
$cat_name = sanitize_text_field($_POST['newcat']);
$my_post ['cat_name'] = $cat_name;
$my_post['post_author'] = get_current_user_id();;
// add post to database
$id = wp_insert_post( $my_post );
endif;
因此,如您所见,我尝试通过将类别链接到 $my_post 和“newcat”输入字段来添加类别。
和形式:
<form action="" method="post" role="form">
<label for="newcat">Category Name</label>
<input type="text" name="newcat" value="" />
</form>
帖子标题和内容正常(已从上面的代码中删除),但类别根本不起作用。
谁能帮我解释一下我做错了什么以及我该如何解决这个问题?
编辑 这也不起作用:
if(isset($_POST['entry']) AND !$_POST['entry'] == ""):
$my_post = array();
$my_post['post_title'] = $_POST['title'];
$my_post['post_content'] = $_POST['entry'];
$my_post['post_status'] = 'publish';
$cat_name = sanitize_text_field( $_POST['newcat'] );
$my_post ['cat_name'] = $cat_name;
$category_id = get_cat_ID( $_POST['newcat'] );
if ( ! $category_id ) {
if ( ! is_admin() ) {
die();
}
$args = array(
'description' => "Category description",
'parent' => 0);
$category_id = wp_insert_term( $_POST['newcat'], "category", $args );
}
$my_post['post_author'] = get_current_user_id();
$my_post['tax_input'] = array('category' => $category_id);
wp_insert_post($my_post);
在这里,如果该特定类别不存在,则该帖子甚至不会添加到 Wordpress!完全没有错误,但也没有发布...
最佳答案
请考虑使用 tax_input
参数来添加类别。
此外,如果没有类别,您可以创建一个类别,但要注意权限限制。
请不要允许所有用户创建类别。例如,检查是否是管理员。
$my_post = array();
$my_post['post_title'] = $_POST['title'];
$my_post['post_content'] = $_POST['entry'];
$my_post['post_status'] = 'publish';
$cat_name = sanitize_text_field( $_POST['newcat'] );
$my_post ['cat_name'] = $cat_name;
$category_id = get_cat_ID( $_POST['newcat'] );
if ( ! $category_id ) {
if ( ! is_admin() ) {
die();
}
$args = [ 'description' => "Category description", 'parent' => 0 ];
$category_id = wp_insert_term( $_POST['newcat'], "category", $args );
}
$my_post['post_author'] = get_current_user_id();
$my_post['tax_input'] = [ 'category' => $category_id ];
wp_insert_post( $my_post );
关于php - 如何通过 PHP 代码将类别添加到 Wordpress 中的帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55960257/