How to Automatically Assign Tags and Categories to Post Submissions

Introduction

Would you like to automatically assign tags and categories to post submissions? With the Post Submissions addon, you can allow your visitors to choose the categories for each post submission. But what if you wanted to assign these categories and even add tags to these posts from within the form as it is submitted? Using PHP, you can easily assign a category or tag to these posts as they are submitted.

Creating the form

First, you’ll need to create a Post Submission form. If you need any assistance with this, please see this documentation.

When you create your form, don’t forget to remove the Categories form field that is automatically added as default when you choose to create the Blog Post Submission form template. Since we’ll be setting these manually with PHP snippets, we don’t want to give this option on our form.

remove the Categories dropdown from the Post Submission form template

Assigning tags and categories

To automatically assign tags and categories to post submissions, we’ll need to add a snippet to our site.

If you need any assistance in adding snippets to your site, please see this tutorial.

/**
 * Assign tags and categories to post submissions
 *
 * @link https://wpforms.com/developers/how-to-automatically-assign-tags-and-categories-to-post-submissions/
 *
 */

function wpf_dev_post_submissions_process( $post_id, $fields, $form_data ) {
      
	// If form ID is 169, run code below
        if ( 649 !== absint( $form_data['id'] ) ) {
        return;
        }
	
	// Craft Category ID is 22 - assign the ID 22 as the category 
	wp_set_object_terms( $post_id, 22, 'category', true );
	
	// Set tag on post to crafty
	wp_set_object_terms( $post_id, 'crafty', 'post_tag' );

    }
add_action( 'wpforms_post_submissions_process', 'wpf_dev_post_submissions_process', 10, 3 );

It’s important that when setting the category for the submission, you’ll need to set it by the category ID number. If you need help in finding your category ID number, please see this article from our friends at WPBeginner.

Since we know this form will specifically be collecting submissions for crafts only, we’re targeting the form id with 649. Then we’ll assign the category id of 22 because this is the ID number for our Crafts category as well as also add the tag crafty to the post.

now this snippet will now assign tags and categories to post submissions

Would you like to add the URL to the post in the confirmation message when the form is submitted? Check out our tutorial on How to Include Post Submissions Post URL in the Confirmation Message.