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

Woocommerce how to display relevant tags under category title

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

<?php

global $product;

?>

<div class="product-tags">

<?php 

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

?>

</div>

示例截图:

好吧,您已经 know/have 类别名称(即 'Coffee Equipment'),因此您可以使用它来获取相关标签,但为了做到这一点,我们将创建一个函数在您的活动主题的 functions.php 中,像这样:

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

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;
}

上面的函数将 return 一个关联数组,其中包含 PRODUCT 类别的相应标签的 tag idtag name

Side Note:
if you need to use it for the blog posts of your wordpress site, then you could change/modify the query by swapping 'post_type' => 'product' argument with 'post_type' => 'posts'. So your query for blog posts would be something like this:

$blog_tag_query = new WP_Query(array('post_type'=>'post','post_status' =>'publish','cat'=>$cat_id,'posts_per_page'=>-1));

If you decide to use it for your blog posts, also remember to change the get_term_link((int)$tag[0], 'product_tag') with get_term_link((int)$tag[0], 'post_tag') in your template.

Now you have a magical function :) that you can use anywhere that you need a list of tags for a specific category!

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

$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>';
};

刚刚测试过,运行良好!您可以根据需要在 html template/markup.

上随意自定义它