wordpress - 如何获得 Woocommerce 顶级产品类别?
问题描述
我正在尝试在主页模板中检索顶级产品类别。我使用了下面的代码,但不知道为什么它不起作用。
<?php
global $post, $product;
$taxonomy = 'product_cat'; //Choose the taxonomy
$terms = get_terms( $taxonomy ); //Get all the terms
foreach ($terms as $term) { //Cycle through terms, one at a time
// Check and see if the term is a top-level parent. If so, display it.
$parent = $term->parent;
if ( $parent=='0' ) {
$term_id = $term->term_id; //Define the term ID
$term_link = get_term_link( $term, $taxonomy ); //Get the link to the archive page for that term
$term_name = $term->name;
echo '<a class="ccats" href="' . $term_link . '"><span class="label">' . $term_name . '</span></a>';
} }
?>
请帮助我获得顶级类别。
解决方案
你可以这样使用:
<?php
$taxonomy = 'product_cat';
$orderby = 'title';
$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 = 1;
$order = 'ASC';
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty,
'order' => $order,
'parent' => 0
);
$terms = get_categories( $args );
foreach ($terms as $term) { //Cycle through terms, one at a time
// Check and see if the term is a top-level parent. If so, display it.
if($term->category_parent == 0){
$term_id = $term->term_id; //Define the term ID
$term_link = get_term_link( $term, $taxonomy ); //Get the link to the archive page for that term
$term_name = $term->name;
echo '<a class="ccats" href="' . $term_link . '"><span class="label">' . $term_name . '</span></a>';
}
}
?>
推荐阅读
- date - 如何在 Azure 数据工厂数据流中添加日期范围
- u-boot - uboot终端上的fatls输出显示什么
- c++ - 如何在我的函数中修复“arr 未在范围内声明”?
- ruby-on-rails - 每个轨道的奇怪输出
- python - 在列表的多维列表中选择随机位置,同时排除特定位置并避免重新创建整个数组
- reactjs - 在 React js 中单击日历时打开没有文本字段的日期选择器对话框
- amazon-web-services - 将 ACM 的 SSL 证书问题添加到 ubuntu 机器上的 Apache 虚拟主机
- wordpress - 如何手动导入 Wordpress xml
- c# - ASP NET 是否有另一种方法可以在不使用 RedirectToAction 的情况下将值从控制器中的当前函数复制到另一个控制器?
- react-native - 如何在堆栈导航中制作透明背景或切换标题