【问题标题】:Display linked product attribute term names in Woocommerce在 Woocommerce 中显示链接的产品属性术语名称
【发布时间】:2019-12-24 17:31:43
【问题描述】:
这是我在产品标题下方显示属性的代码。我怎样才能像链接到此属性的存档页面一样显示它?
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
global $product;
$brand_name = $product->get_attribute('Autor');
echo '<div class ="author-product">';
if( $brand_name )
echo $brand_name;
echo '</div>';
}
【问题讨论】:
标签:
php
wordpress
woocommerce
custom-taxonomy
taxonomy-terms
【解决方案1】:
首先,$product->get_attribute('Autor') 可以给出多个逗号分隔的术语名称。
下面,我们为每个术语名称添加术语链接(如果有多个):
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
global $product;
$taxonomy = 'pa_autor'; // <== The product attribute taxonomy
$linked_terms = []; // Initializing
if ( $term_names = $product->get_attribute($taxonomy) ) {
// Loop through the term names
foreach( explode(', ', $term_names) as $term_name ) {
$term_id = get_term_by('name', $term_name, $taxonomy)->term_id; // get the term ID
$term_link = get_term_link( $term_id, $taxonomy ); // get the term link
$linked_terms[] = '<a href="' . $term_link . '">' . $term_name . '</a>';
}
// Output
echo '<div class ="author-product">' . implode(', ', $linked_terms) . '</div>';
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。