WP_insert_term how to insert multiple values as taxonomny term?

I would build the input fields for terms as array of inputs. Like this (note the [] inthe name attribute:

<input name="input_name[]" type="text" value="">
<input name="input_name[]" type="text" value="">
<input name="input_name[]" type="text" value="">

Then, in PHP:

//Now $_POST['input_name']; is an array
//get the array and sanitize it
$input_terms = array_map( 'sanitize_text_field', $_POST['input_name'] );
//Set the array of terms for later use on wp_set_object_terms
$terms = array();
foreach( $input_terms as $term ) {

    $existent_term = term_exists( $term, 'the_tax' );

    if( $existent_term && isset($existent_term['term_id']) ) {

        $term_id = $existent_term['term_id'];

    } else {

        //intert the term if it doesn't exsit
        $term = wp_insert_term(
            $term, // the term 
            'the_tax' // the taxonomy
        );
        if( !is_wp_error($term ) && isset($term['term_id']) ) {
             $term_id = $term['term_id'];
        } 

   }

   //Fill the array of terms for later use on wp_set_object_terms
   $terms[] = (int) $term_id;

}

//I assume that $listing_id is correct, you didn't shou it in your code
wp_set_object_terms( $listing_id, $terms, 'the_tax' );

UPDATE

I think is not very good approach, but as you asked about it:

<input name="input_name1" type="text" value="">
<input name="input_name2" type="text" value="">
<input name="input_name3" type="text" value="">

Then, in PHP:

//Populate an array with the input fields
$input_terms = array();
$input_terms[] = sanitize_text_field( $_POST['input_name1'] );
$input_terms[] = sanitize_text_field( $_POST['input_name2'] );
$input_terms[] = sanitize_text_field( $_POST['input_name3'] );

//Set the array of terms for later use on wp_set_object_terms
$terms = array();
foreach( $input_terms as $term ) {

    $existent_term = term_exists( $term, 'the_tax' );

    if( $existent_term && isset($existent_term['term_id']) ) {

        $term_id = $existent_term['term_id'];

    } else {

        //intert the term if it doesn't exsit
        $term = wp_insert_term(
            $term, // the term 
            'the_tax' // the taxonomy
        );
        if( !is_wp_error($term ) && isset($term['term_id']) ) {
             $term_id = $term['term_id'];
        } 

   }

   //Fill the array of terms for later use on wp_set_object_terms
   $terms[] = (int) $term_id;

}

//I assume that $listing_id is correct, you didn't shou it in your code
wp_set_object_terms( $listing_id, $terms, 'the_tax' );

NOTE: You don’t need the str_replace function to replace white spaces for “-“. wp_insert_term generates the slug from the term name.

Leave a Comment