本文介绍了在 Woocommerce 中显示链接的产品属性术语名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,用于在产品标题下方显示属性.如何将其显示为指向此属性存档页面的链接?
This is my code for display an atributte below a product title. How can I display it like a link to archive page of this attributte?
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>';
}
推荐答案
首先,$product->get_attribute('Autor')
可以给出多个逗号分隔的术语名称.
下面,我们为每个术语名称添加术语链接(如果有多个):
Below, we add the term link to each term name (if there is more than one):
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 文件中.经测试有效.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
这篇关于在 Woocommerce 中显示链接的产品属性术语名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!