要獲得的屬性值,你需要使用get_terms()
,裏面作爲參數的WC產品屬性蛞蝓爲pa_size
,pa_color
...所以顯示每個對應屬性的值,你將需要第二個foreach循環。
所以,你的代碼可能是這樣的:
if (!function_exists('shop_attributes_in_loop')) {
function shop_attributes_in_loop(){
global $product;
//Getting product attributes
$product_attributes = $product->get_attributes();
if(!empty($product_attributes)){
//Getting product attributes slugs
$product_attribute_slugs = array_keys($product_attributes);
$count_slug = 0;
echo '<div class="product_attributes">';
foreach ($product_attribute_slugs as $product_attribute_slug){
$count_slug++;
// Removing "pa_" from attribute slug and adding a cap to first letter
$attribute_name = ucfirst(str_replace('pa_', '', $product_attribute_slug));
echo $attribute_name . ' (';
## ===> ===> // Getting the product attribute values
$attribute_values = get_terms($product_attribute_slug);
$count_value = 0;
foreach($attribute_values as $attribute_value){
$count_value++;
$attribute_name_value = $attribute_value->name; // name value
$attribute_slug_value = $attribute_value->slug; // slug value
$attribute_slug_value = $attribute_value->term_id; // ID value
// Displaying HERE the "names" values for an attribute
echo $attribute_name_value;
if($count_value != count($attribute_values)) echo ', ';
}
if($count_slug != count($product_attribute_slugs)) echo '), ';
else echo ').';
}
echo '</div>';
}
}
}
add_action('woocommerce_after_shop_loop_item', 'shop_attributes_in_loop');
,並顯示例如像這樣(爲pa_color
和pa_size
名值):
Color (Black, Blue, Green), Size (30, 32, 34, 36, 38, 40, 42, 44).
代碼進入你活動的子主題(活動主題或任何插件文件)的function.php文件中。
該代碼已經過測試並且可以正常工作。
很難知道你在問什麼,因爲它是目前寫的。 – Demitrian
此代碼顯示atributte字段的名稱。 我想代碼顯示屬性值(不是字段的名稱) 現在清除? – Fninja