I have created a custom taxonomy and registered it. I want the taxonomy maximum level should me 2. i.e. Parent => child => sub-child. How to set level??
1 Answer
You can't set a level when you create the taxonomy.
The only way to enforce a level is by watching the term creation: Filter create_term
; that's the earliest filter that allows us to change parent term ID. For no obvious reasons the filter pre_insert_term
is lacking that information … it would probably too easy.
Then change the parent term ID if the current on is already a second level ID.
Sample code, not tested:
add_action( 'create_term', function( $term_id, $tt_id, $taxonomy ) {
$term = get_term( $term_id );
// Nothing to do.
if ( empty( $term->parent ) )
return;
$parent = get_term( $term->parent, $taxonomy );
// This is a second level term, that's okay.
if ( empty( $parent->parent ) )
return;
wp_update_term( $term_id, $taxonomy, [ 'parent' => $parent->term_id ] );
}, 10, 3 );
-
It creates the term then checks the parent. This is not a solution. I want to check if the term which is going to create has hierarchical level 2? If yes then give error msg else create the term. Jan 5, 2017 at 11:42
-
@Deepakmodi The parent ID is not available in an earlier action. So you can at best delete the term here.– fuxia ♦Jan 5, 2017 at 11:44
-
I don't know the solution yet.. But this method don't looks perfect as it allows to create the term. And then i have to delete that term. This is not effective way of doing. Better we have to not allow the term to create with pre_insert_term hook. But i don't know how to. Jan 6, 2017 at 5:07