我会将术语的输入字段构建为输入数组。像这样(注意[]
在名称属性中:
<input name="input_name[]" type="text" value="">
<input name="input_name[]" type="text" value="">
<input name="input_name[]" type="text" value="">
然后,在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
我认为这不是一个很好的方法,但正如您所问:
<input name="input_name1" type="text" value="">
<input name="input_name2" type="text" value="">
<input name="input_name3" type="text" value="">
然后,在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\' );
注意:您不需要str\\u replace函数来替换“-”的空格。
wp_insert_term
从术语名称生成slug。