Let users create a new custom taxonomy entry from frontend (without creating a post)

I have created a custom taxonomy called “Club” (a group of people). This enables me to group posts from contributors (like tags). I use the plugin “Quick Post Widget” to let enter their posts form frontend. In Quick Post Widget’s form they can choose their “Club” (or enter a new one).

Here is my question: How can I let contributers just enter a new “Club” from the frontend, without actually creating a new post. This would be much the same functionality like creating a new tag from the frontend. (i.e: a single input field with a ‘create’ button (submit)).

I have been searching the internet for a simple solution, but did not succeed. I hope you can help me…

1 Answer
1

It’s much simpler than you think.

The function you will be dealing with is wp_insert_term as I am assuming you only want to provide basic functionality to add a new term (club) and not update terms I won’t cover the wp_update_term function now.

The example below is very basic and is intended to be that way for brevity and clarity. You can essentially copy and paste the following snippet into an appropriate place within your theme file(s) such as your sidebar.php template for instance.

<?php

// Check to see if correct form is being submitted, if so continue to process
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "new_term") {

    // Check to see if input field for new term is set 
    if (isset ($_POST['term'])) {

        // If set, stores user input in variable
        $new_term =  $_POST['term'];

        // Function to handle inserting of new term into taxonomy
        wp_insert_term(

          // The term (user input)
          $new_term,

          // The club taxonomy
          'club'        

        );

    } else { 

        // Else throw an error message
        echo 'Please enter a club name!';     

    }

}

?>

<form id="insert_term" name="insert_term" method="post" action=""> 

    <input type="text" value="" name="term" id="term" /> 
    <input type="submit" value="Add Club" id="submit" name="submit" />
    <input type="hidden" name="action" value="new_term" />

</form> 

NOTE

The above code makes no assumptions about security, as to whether or not users must be logged in to see and access the form above. If so you would consider applying the the is_user_logged_in function as a precautionary step.

You may also wish to apply some data validation/sensitization to the form input above of which you can read more here at the codex: Data Validation

Hopefully this sets you on the right path.

Leave a Comment