你不能使用get_category() https://developer.wordpress.org/reference/functions/get_categories/ or get_term() https://developer.wordpress.org/reference/functions/get_terms/直接凭身份证到处走就可以了。您需要使用列出的更多参数in here https://developer.wordpress.org/reference/functions/get_terms/ (见下面的例子)。在模板上,我认为这也取决于所显示的产品(如果它们有此类别或子类别)。
来检索想要的类别对象你需要这样做类别蛞蝓你会使用get_category_by_slug('the_slug') https://codex.wordpress.org/Function_Reference/get_category_by_slug反而。然后您可以使用以下命令检索 ID:
$idObj = get_category_by_slug('my_category_slug');
$id = $idObj->term_id;
其他有用的 WordPress 功能:
要根据类别 ID 检索类别名称,您需要使用get_the_category_by_ID() https://developer.wordpress.org/reference/functions/get_the_category_by_id/.
您还可以通过以下方式检索 ID分类名称你会使用get_cat_ID( 'cat_name' ) https://codex.wordpress.org/Function_Reference/get_cat_ID.
列出产品类别和子类别get_category() https://developer.wordpress.org/reference/functions/get_categories/ (例子):
这是一个基于函数的示例这个线程 https://stackoverflow.com/questions/21009516/get-categories-from-wordpress-woocommerce/21012252#21012252,这将列出所有产品类别和子类别(到处):
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() ;?>
这将显示按层次排序的所有类别和子类别Name,以及每个类别或子类别的相应链接。
然后你还可以使用get_term_by() https://codex.wordpress.org/Function_Reference/get_term_by获取类别名称或别名:
$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
然后现在您将能够构建自己的功能,以满足您的需求......
参考:
- 从 Wordpress Woocommerce 获取类别 https://stackoverflow.com/questions/21009516/get-categories-from-wordpress-woocommerce/21012252#21012252
- 代码参考 > 函数 > get_categories()* https://developer.wordpress.org/reference/functions/get_categories/
- 代码参考 > 函数 > get_terms()(和所有可选参数)* https://developer.wordpress.org/reference/functions/get_terms/
- 代码参考 > 函数 get_term_by() https://codex.wordpress.org/Function_Reference/get_term_by