通过原始SQL查询插入分类术语很困难,不鼓励使用核心wp_insert_term
而是函数。
假设您有一系列大陆/国家术语:
$countries_list = array(
\'Europe\' => array(
\'Austria\', \'France\', \'Italy\', \'Germany\', \'Spain\', \'United Kingdom\'
)
);
foreach ( $countries_list as $continent => $countries ) {
// get term object for continent
$parent = get_term_by( \'slug\', sanitize_title( $continent ), \'category\' );
if ( empty( $parent ) ) {
// continent term doesn\'t exist, let\'s create it
$parent_a = wp_insert_term( $continent, \'category\' );
if ( ! is_array( $parent_a ) ) continue;
// get term object for the just created continent term
$parent = get_term( $parent_a->term_id );
}
// loop countries to add the related terms
foreach ( $countries as $country ) {
// do nothing for current country if the related term already exists
// see http://codex.wordpress.org/Function_Reference/term_exists
if ( term_exists( sanitize_title( $country ), \'category\', $parent->term_id ) ) {
continue;
}
// insert the country term using continent as parent
wp_insert_term( $country, \'category\', array( \'parent\' => $parent->term_id ) );
}
}
当然,这是一个资源非常昂贵的代码,即使代码进行了检查以避免多次添加术语,也应该确保此代码只运行一次,以避免严重的性能问题。
要设置一次运行脚本,请查看this Q/A.