WordPress的WooCommerce显示个别产品的嵌套产品类别
问题描述:
我有一个WordPress的WooCommerce网站,销售汽车零部件。对于每个零件(产品),我创建了可分配给零件的独特产品类别。所以例如前大灯(部分)可以来自3门1999蓝色阿尔法罗密欧156 1.1汽油手册。WordPress的WooCommerce显示个别产品的嵌套产品类别
在单个产品页面上,我想显示仅与本部分关联的产品类别的嵌套列表。所以当我标记一个部分时,我会有一个嵌套的视图,如下图所示。
但是,我目前的代码显示在第二张图片下方,显示了所有与其相关的产品类别,包括这部分。从下面的第二张图中可以看出,我有许多其他零件分配给其他汽车制造商,并且它们都显示为这部分。我只希望本部分显示与本部分相关的产品类别。因此,在创建它应该只显示阿尔法罗密欧 - 而不是所有其他产品类别,其中有部分内容,无论他们在这部分标记。
任何人都可以请帮忙吗?
当前代码
<?php
$woocCategoryTerms = get_terms('product_cat', array(
'order' => 'ASC',
'hide_empty' => true, // (boolean)
'parent' => 0, // (integer) Get direct children of this term (only terms whose explicit parent is this value). If 0 is passed, only top-level terms are returned. Default is an empty string.
'hierarchical' => true, // (boolean) Whether to include terms that have non-empty descendants (even if 'hide_empty' is set to true).
));
foreach($woocCategoryTerms as $wooCategoryTerm) :
?>
<ul>
<li>
<a href="<?php echo get_term_link($wooCategoryTerm -> slug, $wooCategoryTerm -> taxonomy); ?>">
<?php
echo $wooCategoryTerm -> name;
?>
</a>
<ul class="wsubcategs">
<?php
$wooSubArgs = array(
'hierarchical' => true,
'hide_empty' => true,
'parent' => $wooCategoryTerm -> term_id,
'taxonomy' => 'product_cat'
);
$wooSubCategories = get_categories($wooSubArgs);
foreach ($wooSubCategories as $wooSubCategory):
?>
<li>
<a href="<?php echo get_term_link($wooSubCategory -> slug, $wooSubCategory -> taxonomy);?>">
<?php
echo $wooSubCategory -> name;
?>
</a>
</li>
<?php
endforeach;
?>
</ul>
</li>
</ul>
<?php
endforeach;
?>
答
get_terms
回报给出了具体的分类,而不是帖子的全部条款。您在这里有几个选择,但我喜欢使用wp_list_categories
的灵活性。它不仅与建设工程类别,但也与自定义分类
下面是从食品为例
<?php
$taxonomy = 'category'; //change to your taxonomy name
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));
// separator between links
$separator = ', ';
if ( !empty($post_terms) && !is_wp_error($post_terms)) {
$term_ids = implode(',' , $post_terms);
$terms = wp_list_categories('title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids);
$terms = rtrim(trim( str_replace('<br />', $separator, $terms)), $separator);
// display post categories
echo $terms;
}
?>
您也可以使用get_the_terms