我正在使用 get_category()
通过 ID 获取类别对象。这里 category 39
是 category 37
的子项。例如,
Courses (37)
- Programming (39)
我的问题是,如果我在 functions.php
中使用 get_category(37 or 39)
,两者都会返回 null
。如果我在 single-product.php
中使用 get_category(37 or 39)
37(根类别)将返回 null。如果我在 add-to-cart/simple.php
中使用相同的调用,两者都将返回一个对象。
WooCommerce 函数将首先被调用,然后是 single-product.php
和 add-to-cart/simple.php
模板。
发生了什么事?
为什么它会根据文件工作?
@编辑
get_term( 37, 'category' );
似乎也失败了
@edit 13/7 - The correct working solution
I managed to solve this issue before reading the answers with:
$category = get_term_by('id', $category_id, 'product_cat');
引用资料:
最佳答案
您不能使用 get_category()
或 get_term()
到处直接带ID。您需要使用列出的更多参数 in here (参见下面的示例)。在模板上,我认为这也取决于显示的产品(如果他们有这个类别或子类别)。
To retrieve the desired category object you will need to do it by category slug and you will use
get_category_by_slug('the_slug')
instead. Then you can retrieve the ID with:$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() ;?>
这将显示您的所有类别和子类别,按名称分层排序,每个类别或子类别都有相应的链接。
Then you can also use get_term_by() to get the category name or 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
那么现在您将能够构建自己的函数来满足您的需求……
引用:
关于php - 无法在 WooCommerce 的某些模板中获取类别对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288298/