从 WooCommerce 中的订单项获取变体属性
Get variation attributes from order items in WooCommerce
我尝试获取购物车中可变产品属性名称的名称,但出了点问题。
我不明白当一个对象被保护时我如何获得变化值
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 ) {
$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>';
}
}
}
应该可以。