[英]Display product attributes on specific Woocommerce product category archives page
[英]Show WooCommerce product attributes in custom home and product category archives
以下代码在产品类别存档页面上显示产品属性,并基于“在特定 Woocommerce 产品类别存档页面上显示产品属性”回答线程。
但是,当我在主页上添加该类别时,它不会显示属性。
我的代码版本:
// Show Attributes on Product Category Page
add_action('woocommerce_after_shop_loop_item','display_loop_product_attribute' );
function display_loop_product_attribute() {
global $product;
//$product_attributes = array('pa_size', 'pa_color');
$product_attributes = array('pa_size');
$attr_output = array();
// Loop through the array of product attributes
foreach( $product_attributes as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
if( $value = $product->get_attribute($taxonomy) ){
// The product attribute label name
$label_name = get_taxonomy($taxonomy)->labels->singular_name;
// Storing attributes for output
$attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
}
}
}
// Output attribute name / value pairs separate by a "<br>"
echo '<div class="product-attributes-custom">'.implode('<br>', $attr_output).'</div>';
}
我不知道如何使它在显示产品的自定义主页和特定产品类别页面上运行。 对于主页,我知道要使用的条件标签是is_home()
......但是我怎样才能让它也适用于产品类别页面呢?
更新 - 以下代码将显示特定产品属性:
is_front_page()
WordPress 条件标签的自定义产品循环的主页is_product_category()
Woocommerce 条件标签定义的产品类别存档页面编码:
add_action('woocommerce_after_shop_loop_item','display_loop_product_attribute' );
function display_loop_product_attribute() {
global $product;
// The Product attribute to be displayed
$product_attributes = array('pa_size');
// The targeted Product category archive pages (slugs)
$categories = array('t-shirts', 'hoodies', 'socks');
$output = array(); // Initializing
// Targetting home page and specific product category archive pages
if( is_front_page() || is_product_category($categories) ) {
// Loop through the array of product attributes
foreach( $product_attributes as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
if( $values = $product->get_attribute($taxonomy) ){
// The product attribute label name
$label_name = get_taxonomy($taxonomy)->labels->singular_name;
// Storing attributes for output
$output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$values.'</span>';
}
}
}
// Output attribute name / value pairs, separate by a "<br>"
echo '<div class="product-attributes-custom">'.implode('<br>', $output).'</div>';
}
}
代码位于您的活动子主题(或活动主题)的 function.php 文件中。 测试和工作。
补充:要在它自己的<span>
标记中格式化每个属性术语名称......
在此行之后插入功能代码:
// The product attribute label name
$label_name = get_taxonomy($taxonomy)->labels->singular_name;
以下:
// convert string of term names to an array
$values = explode(', ', $values);
// Format each and set back to a string
$values = '<span>' . implode('</span> <span>', $values) . '</span>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.