我尝试获取购物车中可变产品属性名称的名称,但出现问题。 我不明白当对象受到保护时如何获得变化值
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$product = $item->get_product();
$accomodation = $product['variation']['attribute_pa_hebergement']; // does not work
}
这是 $product 中对象返回的一部分
WC_Product_Variation Object
(
[post_type:protected] => product_variation
[parent_data:protected] => Array
(
[title] => test
[status] => publish
[sku] =>
[tax_class] =>
[shipping_class_id] => 0
)
[object_type:protected] => product
[cache_group:protected] => products
[data:protected] => Array
(
[name] => test
[slug] => test-14
...
[attributes] => Array
(
[pa_hebergement] => chambre-double-140e
[pa_parking] => 1-place-35e
[pa_tarifs] => tarif-jeune
)
[default_attributes] => Array
(
)
尝试使用
WC_Product
方法get_attributes()
,例如:
// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
// Target product variations
if ( $item->get_variation_id() ) {
$product = $item->get_product(); // Get the product Object
// Loop through product attributes
foreach ( $product->get_attributes() as $attribute => $value ) {
// Get attribute label name
$label = wc_attribute_label($attribute);
// Get attribute name value
$name = term_exists( $value, $attribute ) ? get_term_by( 'slug', $value, $attribute )->name : $value;
// Display
echo '<p><strong>' . $label . '</strong>: ' . $name . '</p>';
}
}
}
应该可以。
这可能会对将来的人有所帮助,下面的代码获取格式化的变体:
foreach ( $order->get_items() as $item_id => $item ) {
if ( $item->get_variation_id() ) {
$product = $item->get_product();
$variations = wc_get_formatted_variation( $product, true );
$item_name = $item_name . "(" . $variations . ")";
}
}