My registered custom taxonomy name is ov-category
..
There is already existing a parent term called Gender
now i want to add a child called Male
:
$parent_term = term_exists( 'Gender', 'ov-category' );
$parent_term_id = $parent_term['term_id']; // get numeric term id
echo $parent_term_id; // shows the correct parent ID, that means term_exists() does work!!
// Inserting the child term 'Male'
wp_insert_term(
'Male', // the term
'ov-category', // the taxonomy
array(
'description'=> '',
'slug' => '',
'parent'=> $parent_term_id
)
);
even if i try to insert a parent-only term it doesnt work. but i can read their correct IDs using term_exists() and those are correct because i checked them in the database. By the way: i added Gender
over the UI. I need a way that those terms are automatically added when my plug-in is installed.
My registered custom taxonomy name is ov-category
..
There is already existing a parent term called Gender
now i want to add a child called Male
:
$parent_term = term_exists( 'Gender', 'ov-category' );
$parent_term_id = $parent_term['term_id']; // get numeric term id
echo $parent_term_id; // shows the correct parent ID, that means term_exists() does work!!
// Inserting the child term 'Male'
wp_insert_term(
'Male', // the term
'ov-category', // the taxonomy
array(
'description'=> '',
'slug' => '',
'parent'=> $parent_term_id
)
);
even if i try to insert a parent-only term it doesnt work. but i can read their correct IDs using term_exists() and those are correct because i checked them in the database. By the way: i added Gender
over the UI. I need a way that those terms are automatically added when my plug-in is installed.
1 Answer
Reset to default 1Thanks to Milo who asked an important question: Where is this code?
I put it below where ive have registered the taxonomy and then it worked:
function register_taxonomy() {
$labels = array(...);
$args = array(...);
register_taxonomy( 'ncategory', null, $args );
$parent_term = term_exists( 'Gender', 'ncategory' ); // array is returned if taxonomy is given
$parent_term_id = $parent_term['term_id']; // get numeric term id
//echo $parent_term_id;
$ret = wp_insert_term(
'Male',
'ncategory',
array(
'description'=> '',
'slug' => '',
'parent'=> $parent_term_id
)
);
echo is_wp_error($ret);
}
term_exists
does not validate the taxonomy, wherewp_insert_term
checks if it's a registered taxonomy.term_exists
will succeed even if the taxonomy isn't registered in the current request, wherewp_insert_term
will fail. – Milo Commented Aug 16, 2017 at 5:47