If you want to auto-create the same term in another taxonomy, the following code should do it:
You’ll add the code to the theme functions file (i.e. functions.php
), and make sure to change the $taxonomies
which is the list of the applicable taxonomy slugs — the taxonomies that you wish to “sync”. Both the $taxonomies
should have the exact same values.
But note that this code is intended for terms that do not have parents; or rather, non-hierarchical taxonomies.
$taxonomies = ['my_tax', 'post_tag'];
foreach ( $taxonomies as $taxonomy ) {
add_action( 'created_' . $taxonomy, 'auto_create_term' );
}
function auto_create_term( $term_id ) {
$term = get_term( $term_id );
if ( ! $term || is_wp_error( $term ) ) {
return false;
}
$taxonomies = ['my_tax', 'post_tag'];
foreach ( $taxonomies as $taxonomy ) {
if ( $taxonomy !== $term->taxonomy ) {
remove_action( 'created_' . $taxonomy, __FUNCTION__ );
wp_insert_term( $term->name, $taxonomy, array(
'description' => $term->description,
'alias_of' => $term->slug,
) );
add_action( 'created_' . $taxonomy, __FUNCTION__ );
}
}
}
What the code is doing: We’re using the created_{taxonomy}
action to auto-clone a term; but we temporarily remove the hook while we’re cloning the term — and then add the hook back after the term is cloned (created in the target taxonomy).