从 WooCommerce 中的订单商品获取变体属性

问题描述 投票:0回答:2

我尝试获取购物车中可变产品属性名称的名称,但出现问题。 我不明白当对象受到保护时如何获得变化值

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
               (
               )
php wordpress woocommerce product orders
2个回答
2
投票

尝试使用

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>';
        }
    }
}

应该可以。


0
投票

这可能会对将来的人有所帮助,下面的代码获取格式化的变体:

   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 . ")";
    }   
    
    }
© www.soinside.com 2019 - 2024. All rights reserved.