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

Create categories and multiple subcategories programmatically

此代码在 wordpress 管理区域中正确显示类别。但没有显示子类别。

我需要为每个类别显示 3 个类别和 3 个子类别?

这是我希望每个类别的内容:

A 类

我在 wordpress 主题的 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']

));

但我收到一个错误:

Parse error: parse error, expecting `')'' in line 57 …

对应'parent'=> term_exists( 'Category A', 'category' )['term_id'].

我做错了什么?

您似乎遗漏了父类别名称的第一个引号,这可能是解析错误的原因,应该是:

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

已编辑评论:

$parent = term_exists( 'Category A', 'category' );
$termId = $parent['term_id'];

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'=> $termId

));

问题是你需要在函数外获取parent term id,以避免错误。您可以通过这种方式轻松完成:

$parent_term_a = term_exists( 'Category A', 'category' ); // array is returned if taxonomy is given
$parent_term_a_id = $parent_term_a['term_id']; // get numeric term id

// First subcategory
wp_insert_term(
    'Sub-category 1', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-1a',
        'parent'=> $parent_term_a_id
    )
);

// Second subcategory
wp_insert_term(
    'Sub-category 2', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-2a',
        'parent'=> $parent_term_a_id
    )
);

// Third subcategory
wp_insert_term(
    'Sub-category 3', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-3a',
        'parent'=> $parent_term_a_id
    )
);

然后您将用于其他 2 组子类别:

// For subcategory group of Category B
$parent_term_b = term_exists( 'Category B', 'category' );
$parent_term_b_id = $parent_term_b['term_id'];

// For subcategory group of Category C
$parent_term_c = term_exists( 'Category C', 'category' );
$parent_term_c_id = $parent_term_c['term_id'];

…以同样的方式(注意为每个子类别设置一个独特的 slug,这意味着总共有 9 个不同的子类别 slug)

参考: