php - Woocommerce如何在类别标题下显示相关标签
问题描述
我想在每个类别标题下显示元标记。我可以看到有这段代码可以显示每个产品的产品标签列表,但我真正想要的是每个类别的产品标签,然后将其显示在页面的类别标题下。
<?php
global $product;
?>
<div class="product-tags">
<?php
echo wc_get_product_tag_list( $product->get_id(), ', ' );
?>
</div>
示例截图:
解决方案
好吧,您已经知道/拥有类别名称(即“咖啡设备”),因此您可以使用它来获取相关标签,但为了做到这一点,我们将在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 id
的PRODUCT类别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')
withget_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
.
推荐阅读
- python - Python Flask 应用程序未重定向
- python - 筛选数据透视表
- javascript - Amcharts -Treemap图表如何获取工具提示值和点击事件
- javascript - 传递给Vuex模块的函数后的Vue TypeScript未定义值
- powershell - 如何使用 Nullable
Powershell 中的类型? - redisson - 使用 Redisson 批处理时,操作的顺序是否有保证?
- php - 为什么 Ajax 代码没有发布到 pho 文件?
- kubernetes - 如何在 OpenShift pod YAML 配置中绑定多个端口?
- django - 如何在不使用 docker-compose.yml 的情况下为多个容器创建单个 Dockerfile?
- python-3.x - 一旦 numPy 数组的元素达到某个值,如何设置执行命令的条件?