从 Wordpress 的前端更新类别 [英] Update category from the front-end in Wordpress
问题描述
我主要根据我找到的教程来完成这项工作.这是一个前端表单,让我在点击提交按钮时更改帖子标题,但我也希望允许更新类别,但我不知道如何让它这样做.
I've got this mostly working based on a tutorial I found. This is a front-end form that let's me change the post title when I hit the submit button, but I also want to allow updating the category and I have no idea how to get it to do that.
我正在使用 wp_dropdown_categories 吐出现有类别的下拉框,如果知道它的名称和 id 是猫"是否有帮助.
I'm using wp_dropdown_categories to spit out a drop-down box of existing categories, and if it helps to know the name and id of that is "cat".
我怀疑可能需要涉及 update_post_meta,但我可能是错的,我不完全确定如何实施.
I suspect update_post_meta might need to be involved, but I could be wrong and I'm not entirely sure how to go about implementing that anyway.
<?php
if(isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
$postTitle = trim($_POST['title']);
$post_id = get_the_ID();
$my_post['ID'] = $post_id;
$template_dir = get_bloginfo('template_directory');
$my_post = array();
$my_post['post_status'] = 'publish';
$my_post['post_title'] = $postTitle;
$my_post['filter'] = true;
wp_update_post( $my_post);
wp_redirect( get_permalink( $post_id ) );
exit;
}
get_header();
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<form action="" id="update-post" method="post">
<label>Post</label>
<input type="text" id="title" name="title" value="<?php echo the_title(); ?>" />
<label>Category</label>
<?php $categories = get_the_category();
$category_id = $categories[0]->cat_ID;?>
<?php wp_dropdown_categories( "show_count=1&hierarchical=1&orderby=name&order=ASC&selected=" . $category_id . "&hide_empty=0&show_option_all=None" ); ?>
<input type="submit" name="submit" value="Submit" />
<?php wp_nonce_field('post_nonce', 'post_nonce_field'); ?>
</form>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
提前致谢!
推荐答案
你可以使用wp_set_object_terms()
.Codex 中的更多信息.
You can use wp_set_object_terms()
. More info in the Codex.
wp_set_object_terms( $post_id, intval( $_POST['cat'] ), 'category', false );
这篇关于从 Wordpress 的前端更新类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!