Skip to content

Instantly share code, notes, and snippets.

@ciccarone
Last active April 5, 2023 11:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ciccarone/e0458b01b4d2904ebcbbe1ebad01f588 to your computer and use it in GitHub Desktop.
Save ciccarone/e0458b01b4d2904ebcbbe1ebad01f588 to your computer and use it in GitHub Desktop.
Programmatically add hierarchical taxonomies in Wordpress
$taxonomy_term = 'example';
$related_terms = array(
__( 'Parent' ) => array(
__( 'Child 1' ),
__( 'Child 2' ),
),
__( 'Parent 2') => array(
__( 'Child 3' ),
__( 'Child 4' ),
),
);
foreach ($related_terms as $key => $term) {
wp_insert_term(
(string)$key,
$taxonomy_term,
array(
'slug' => sanitize_title_with_dashes((string)$key),
)
);
$parent_term = term_exists( $key, $taxonomy_term );
$term_id = $parent_term['term_id'];
foreach ($term as $term_value) {
wp_insert_term(
$term_value,
$taxonomy_term,
array(
'slug' => sanitize_title_with_dashes( $term_value ),
'parent'=> $term_id
)
);
}
}
@richardscholtens
Copy link

Thank you for sharing this. Works like a charm!

@richardscholtens
Copy link

With help of your code I was able to adapt it to also programmatically create Wordpress terms that are nested three levels deep.
I created a fork from this github page so that other people may also benefit from it.

https://gist.github.com/richardscholtens/b87ab3496e2460188fff26ae8fc3e27f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment