Update category from the front-end in Wordpress

2019-04-17 23:16发布

问题:

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.

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".

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(); ?>

Thanks in advance!

回答1:

You can use wp_set_object_terms(). More info in the Codex.

wp_set_object_terms( $post_id, intval( $_POST['cat'] ), 'category', false );