如何解决显示为带有短代码的产品设置的WooCommerce产品标签名称
正如标题所述,我正在寻找一个短代码,可以用来显示特定产品的标签。 我所有的产品都只设置了一个产品标签。
例如,如果ID为1250的产品的标签为“ Horse”,我需要一种方法来输入一个简短的代码来指定产品的ID并显示您的相应标签。在示例中,短代码应在屏幕上显示“马”一词
尝试修改以下代码以实现它:
$terms = wp_get_post_terms( get_the_id(),'product_tag' );
if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term,'product_tag' );
$output[] = '.$term_name.';
}
$output = implode( ',',$output );
echo $output;
}
但是我没有足够的知识来实现它
感谢您的帮助。
解决方法
如果每个产品只设置了一个产品标签,则以下简短代码功能将输出当前产品的产品标签术语名称集(如果为一个产品设置了多个术语,则输出逗号分隔的术语名称字符串) )。
它也适用于已定义的产品ID作为短代码中的参数(请参见用法示例)。功能代码:
add_shortcode( 'wc_product_tag','get_tag_term_name_for_product_id' );
function get_tag_term_name_for_product_id( $atts ) {
// Shortcode attribute (or argument)
extract( shortcode_atts( array(
'taxonomy' => 'product_tag',// The WooCommerce "product tag" taxonomy (as default)
'product_id' => get_the_id(),// The current product Id (as default)
),$atts,'wc_product_tag' ) );
$term_names = (array) wp_get_post_terms( $product_id,$taxonomy,array('fields' => 'names') );
if( ! empty($term_names) ){
// return a term name or multiple term names (in a coma separated string)
return implode(',',$term_names);
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。
用法示例:
- 对于当前产品:
[wc_product_tag]
或在php中:echo do_shortcode('[wc_product_tag]');
- 对于已定义的产品ID:
[wc_product_tag product_id="37"]
或在php中:echo do_shortcode('[wc_product_tag product_id="37"]');
这也适用于任何产品自定义分类法,如WooCommerce产品类别…
要显示为您需要替换的产品设置的 WooCommerce产品类别术语名称:
'taxonomy' => 'product_tag',// The WooCommerce "Product Tag" taxonomy (as default)
通过以下行:
'taxonomy' => 'product_cat',// The WooCommerce "Product Category" taxonomy (as default)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。