以编程方式创建类别和子类别

时间:2016-07-28 作者:FRQ6692

我用此代码创建了具有品牌的类别。我一共有3个类别,每个类别有3个子类别。

how to output 3 category and 3 subcategories for each category?

作用PHP代码

function insert_category() {
if(!term_exists(\'brand\')) {
    wp_insert_term(
        \'Brand\',
        \'category\',
        array(
          \'description\' => \'sample category.\',
          \'slug\'        => \'brand\'
        )
    );
  }
 }
add_action( \'after_setup_theme\', \'insert_category\' );

1 个回复
SO网友:Gregory Schultz

如果您的问题是这样的:

A类-子类1-子类2-子类3

然后在主题中创建以下内容functions.php:

//create the main category
wp_insert_term(

// the name of the category
\'Category A\', 

// the taxonomy, which in this case if category (don\'t change)
\'category\', 

array(

// what to use in the url for term archive
\'slug\' => \'category-a\',  
));
然后针对每个子类别:

wp_insert_term(

// the name of the sub-category
\'Sub-category 1\', 

// the taxonomy \'category\' (don\'t change)
\'category\',

array(
// what to use in the url for term archive
\'slug\' => \'sub-cat-1\', 

// link with main category. In the case, become a child of the "Category A" parent  
\'parent\'=> term_exists( \'Category A\', \'category\' )[\'term_id\']

));
希望这有帮助。