此代码在 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']
));
但我收到错误:
解析错误:解析错误,第 57 行需要 '')'' ...
对应
'parent'=> term_exists( 'Category A', 'category' )['term_id']
。
我做错了什么?
问题是您需要在函数外部获取父项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'];
…以同样的方式(注意为每个子类别都有一个独特的slugs,这意味着总共有9个不同的子类别slugs)… 参考:
// 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
));