Last active
June 20, 2016 05:32
-
-
Save alpha1/d6b929e0c386082a934f2cdbfb0e389c to your computer and use it in GitHub Desktop.
Wordpress: Mass Insert Terms (Including Children and Meta)
This file contains hidden or 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
<?php | |
function wpcrmio_mass_insert_terms( $taxonomy, $terms_array = array() ){ | |
/* | |
$terms_array = array( | |
'slug' => array( | |
'name' => '', | |
'description' => '', | |
'meta' => '', | |
'children' => array( | |
'slug' => array( | |
'name' => '', | |
'description' => '', | |
'meta' => '', | |
), | |
), | |
), | |
); | |
*/ | |
if( !is_array( $terms_array ) ){ | |
return false; | |
} | |
foreach( $terms_array as $slug => $data ){ | |
$args = array( 'slug' => $slug ); | |
//add the following attributes to | |
if( isset( $data['description'] ) ){ | |
$args['description'] = $data['description']; | |
} | |
if( isset( $data['parent'] ) ){ | |
$args['parent'] = $data['parent']; | |
} | |
if( isset( $data['alias_of'] ) ){ | |
$args['alias_of'] = $data['alias_of']; | |
} | |
$results = wp_insert_term( $data['name'], $taxonomy, $args ); | |
//deletes the cash, just in case. | |
delete_option("{taxonomy}_children"); | |
if( !is_wp_error( $results) ){ | |
if( $data['meta'] ){ | |
foreach( $data['meta'] as $meta_key => $meta_value ){ | |
update_term_meta( $results['term_id'], $meta_key, $meta_value ); | |
} | |
} | |
if( $data['children'] ){ | |
array_walk( $data['children'], function( &$child ) use ( $results ) { | |
return array_merge( $child, array( 'parent' => $results['term_id'] ) ); | |
} ); | |
wpcrmio_mass_insert_terms( $taxonomy, $data['children'] ); | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment