[英]Display product attributes on specific Woocommerce product category archives page
我想在類別頁面上顯示兩個屬性,僅在特定類別上顯示屬性名稱和值。
我找到的這段代碼顯示了屬性的標簽,但正在復制值,而且我真的很費勁來顯示類別變量。 任何幫助是極大的贊賞。
編碼:
add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
global $product;
$product_attributes = array( 'pa_set', 'pa_team');
$attr_output = array();
// Loop through the array of product attributes
foreach( $product_attributes as $taxonomy ){
if( taxonomy_exists($taxonomy) ){
$label_name = get_taxonomy( $taxonomy )->labels->singular_name;
$value = $product->get_attribute('pa_set');
if( ! empty($value) ){
// 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">'.implode( '<br>', $attr_output
).'</div>';
}
更新- 問題來自以下行,其中產品屬性屬性值始終用於相同的產品屬性:
$value = $product->get_attribute( 'pa_set' );
應該是這樣的:
$value = $product->get_attribute( $taxonomy );
完整的重新訪問代碼將是:
add_action('woocommerce_after_shop_loop_item','display_loop_product_attribute' );
function display_loop_product_attribute() {
global $product;
$product_attributes = array('pa_set', 'pa_team'); // Defined product attribute taxonomies.
$attr_output = array(); // Initializing
// 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 = wc_attribute_label($taxonomy);
// 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">'.implode('<br>', $attr_output).'</div>';
}
代碼位於活動子主題(或活動主題)的 function.php 文件中。 測試和工作。
定位產品類別存檔頁面:
您將在IF
語句的函數內使用條件標記is_product_category()
...
對於特定的產品類別存檔頁面,您可以按照此處的說明在數組中的函數內設置它們,例如:
if( is_product_category( array('chairs', 'beds') ) {
// Here go the code to be displayed
}
您只需要在數組中設置正確的產品類別 slug...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.