[英]Get only post terms for Woocommerce product tags?
My function outputs all used Woocommerce product tags, on every product.我的函数在每个产品上输出所有使用过的 Woocommerce 产品标签。
How can I sort out/output only tags that every single product has selected from backend?如何只整理/输出每个产品从后端选择的标签?
Here is my code:这是我的代码:
add_action( 'woocommerce_before_shop_loop_item', 'woocommerce_product_loop_tags', 5 );
add_action( 'woocommerce_product_thumbnails', 'woocommerce_product_loop_tags', 5 );
function woocommerce_product_loop_tags() {
global $post, $product;
if ( is_array (get_terms( 'product_tag' ))) {
$tags = get_terms( 'product_tag' , 'orderby=id' );
echo '<span class="badge-cloud">';
foreach($tags as $tag) {
echo '<span rel="tag" class="fl-badge '.$tag->slug.'"><p>'.$tag->name.'</p></span>';
}
echo '</span>';
}
}
The correct way is o use wp_get_post_terms()
where you can set the post ID for a given taxonomy to get the terms for this specific post ID.正确的方法是使用wp_get_post_terms()
,您可以在其中设置给定分类法的帖子 ID 以获取此特定帖子 ID 的术语。 So your code should be:所以你的代码应该是:
add_action( 'woocommerce_before_shop_loop_item', 'woocommerce_product_loop_tags', 5 );
add_action( 'woocommerce_product_thumbnails', 'woocommerce_product_loop_tags', 5 );
function woocommerce_product_loop_tags() {
global $post;
$taxonomy = 'product_tag';
$args = 'orderby=id';
$product_tags = wp_get_post_terms( $post->ID, $taxonomy, $args );
if ( count($product_tags) > 0 ){
echo '<span class="badge-cloud">';
foreach( $product_tags as $term )
echo '<span rel="tag" class="fl-badge '.$term->slug.'"><p>'.$term->name.'</p></span>';
echo '</span>';
}
}
Code goes in function.php file of your active child theme (active theme or in any plugin file).代码位于活动子主题(活动主题或任何插件文件)的 function.php 文件中。
Tested and works.测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.