Last active
April 5, 2023 11:12
-
-
Save ciccarone/e0458b01b4d2904ebcbbe1ebad01f588 to your computer and use it in GitHub Desktop.
Programmatically add hierarchical taxonomies in Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 | |
) | |
); | |
} | |
} |
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
Thank you for sharing this. Works like a charm!