您不能在任何地方直接使用带有 ID 的 get_category() 或 get_term()。您需要使用列出的更多参数in here(参见下面的示例)。在模板上,我认为这也取决于显示的产品(如果他们有这个类别或子类别)。
要检索所需的category object,您需要通过category slug 来完成,您将使用get_category_by_slug('the_slug') 代替。然后您可以通过以下方式检索 ID:
$idObj = get_category_by_slug('my_category_slug');
$id = $idObj->term_id;
其他有用的 WordPress 功能:
要根据类别 ID 检索类别名称,您需要使用 get_the_category_by_ID()。
您还可以通过 类别名称 检索 ID,您将使用 get_cat_ID( 'cat_name' )。
使用get_category() 列出产品类别和子类别(示例):
这是一个基于this thread 的函数示例,它将列出所有产品类别和子类别(无处不在):
function products_cats_subcats(){
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$all_categories = get_categories( $args );
echo '<ul>';
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<li><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a></li>';
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
echo '<ol>';
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<li><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">' . $sub_category->name .'</a></li>';
}
}
echo '</ol>';
}
}
echo '</ul>';
}
要使用它,只需将其放在您想要的位置:<?php products_cats_subcats() ;?>
这将显示按名称分层排序的所有类别和子类别,以及每个类别或子类别的相应链接。
那么你也可以使用get_term_by()来获取类别名称或slug:
$term = get_term_by('id', $term_id, 'product_cat', 'ARRAY_A');
$term['name']; //get the WC category name
$term['slug']; //get the WC category slug
那么现在您将能够构建自己的功能,以满足您的需求......
参考: