首页 > 解决方案 > Woocommerce如何在类别标题下显示相关标签

问题描述

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

<?php

global $product;

?>

<div class="product-tags">

<?php 

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

?>

</div>

示例截图:

在此处输入图像描述

标签: phpwordpresswoocommercetagswordpress-theming

解决方案


好吧,您已经知道/拥有类别名称(即“咖啡设备”),因此您可以使用它来获取相关标签,但为了做到这一点,我们将在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;
}

上面的函数将返回一个关联数组,其中包含您tag idPRODUCT类别tag name的相应标签。

旁注:
如果您需要将它用于您的 wordpress 网站的博客文章,那么您可以通过交换'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')with 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>';
};

刚刚经过测试,它可以无缝运行!随意根据需要在您的html template/markup.


推荐阅读