Woocommerce 如何在类别标题下显示相关标签

时间:2021-07-25 12:42:37

标签: wordpress woocommerce tags wordpress-theming woocommerce-theming

我想在每个类别标题下显示元标记。我可以看到有这段代码可以显示每个产品的产品标签列表,但我真正想要的是每个类别的产品标签,然后将其显示在页面的类别标题下。

<?php

global $product;

?>

<div class="product-tags">

<?php 

echo wc_get_product_tag_list( $product->get_id(), ', ' ); 

?>

</div>

示例截图:

enter image description here

1 个答案:

答案 0 :(得分:4)

好吧,您已经知道/拥有类别名称(即“咖啡设备”),因此您可以使用它来获取相关标签,但为此,我们将在 {{1 }} 您的活动主题,如下所示:

以下代码将转到您的活动主题的 functions.php 文件:

functions.php

上面的函数将返回一个关联数组,其中包含您的 PRODUCT 类别的相应标签的 function your_theme_get_tags_based_on_cat($cat_name) { $cat_id = get_cat_ID($cat_name); $tag_query = new WP_Query(array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $cat_id, 'operator' => 'IN' ) ) )); $all_tags = array(); while ($tag_query->have_posts()) { $tag_query->the_post(); $producttags = get_the_tags(); if ($producttags) { foreach ((array)$producttags as $tag_obj) { $all_tags[] = $tag_obj->term_id . '-' . $tag_obj->name; } } }; $tags_array = array_unique($all_tags); $new_array = array_map(function ($val) { return explode("-", $val); }, $tags_array); return new_array; } tag id

<块引用>

旁注:
如果您需要将它用于 wordpress 网站的博客文章,那么您可以通过将 tag name 参数与 'post_type' => 'product' 交换来更改/修改查询。因此,您对博客文章的查询将是这样的:

'post_type' => 'posts'

如果您决定将其用于您的博客文章,还请记住将模板中的 $blog_tag_query = new WP_Query(array('post_type'=>'post','post_status' =>'publish','cat'=>$cat_id,'posts_per_page'=>-1)); 更改为 get_term_link((int)$tag[0], 'product_tag')

<块引用>

现在你有一个神奇的功能:)你可以在任何需要特定类别标签列表的地方使用它!

那么让我们在您的页面模板中使用我们的函数来填充当前类别的相应标签,如下所示:

get_term_link((int)$tag[0], 'post_tag')

刚刚测试过,可以无缝运行!您可以根据需要在您的 $cat_name = 'Coffee Equipment'; $tags_array = your_theme_get_tags_based_on_cat($cat_name); foreach ($tags_array as $tag) { echo '<a class="item" href="' . get_term_link((int)$tag[0], 'product_tag') . '">' . $tag[1] . '</a>'; }; 上随意自定义。