以下代码显示产品类别归档页面上的产品属性,并基于“Display product attributes on specific Woocommerce product category archives page”答案线程。
但是,当我在主页上添加该类别时,它不会显示属性。
我的代码版本:
// 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>';
相关:Display product attributes on specific Woocommerce product category archives page