我正在使用get_category()
根据其id获取category对象。这里category 39
是category 37
的子对象。例如,
Courses (37)
- Programming (39)
我的问题是,如果我在
get_category(37 or 39)
中使用functions.php
,两者都将返回null
。如果在get_category(37 or 39)
37(根类别)中使用single-product.php
将返回空值。如果我在add-to-cart/simple.php
中使用相同的调用,两者都将返回一个对象。woomerce函数将首先调用,然后调用
single-product.php
模板,然后调用add-to-cart/simple.php
模板。怎么回事?
为什么依赖于文件?
@编辑
get_term( 37, 'category' );
似乎也失败了
@编辑13/7-正确的工作解决方案
在阅读答案之前,我设法解决了这个问题:
$category = get_term_by('id', $category_id, 'product_cat');
参考文献:
Function get_term_by()
Show category list with titles
How to get the category name from an id product in woocommerce
最佳答案
不能在任何地方直接使用带id的get_category()
或get_term()
。您需要使用列出的更多参数in here(请参见下面的示例)。在模板上,我认为还取决于显示的产品(如果它们有这个类别或子类别)。
要检索所需的category对象,您需要按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()来获取类别名称或段塞:
$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
现在你将能够建立自己的功能,满足你的需要…
参考:
Get categories from Wordpress Woocommerce
Code Reference > Functions > get_categories()*
Code Reference > Functions > get_terms() (and all optional arguments)*
Code Reference > Function get_term_by()