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

FRQ*_*692 3 php wordpress categories

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

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

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

A类

  • 子类别 1
  • 子类别 2
  • 子类别 3

我在 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',  
 ));`
Run Code Online (Sandbox Code Playgroud)

然后对于每个子类别:

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']

));
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

解析错误:解析错误,期望在第 57 行出现 `')'' ...

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

我做错了什么?

Loi*_*tec 5

问题是您需要在函数之外获取父术语 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
    )
);
Run Code Online (Sandbox Code Playgroud)

然后您将用于其他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'];
Run Code Online (Sandbox Code Playgroud)

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

参考: