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

标签 php wordpress woocommerce product orders

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

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

应该可以。

关于php - 从 WooCommerce 中的订单商品获取变体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66746825/

相关文章:

php - 内连接 : where clause is too ambiguous

php - 不能使用函数返回值

javascript - Wordpress + JQuery UI 选项卡 + 动态改变选项卡宽度

php - 当一切都已安装但仍然无法正常工作时,如何使用 LAMP 解决 Wordpress

如果 JavaScript 替换方法破坏了嵌套,它不会删除结束标记,如正则表达式中编码的那样

php - WooCommerce 客户完成订单电子邮件通知中基于产品类别的条件文本

php - 如何在 PHP 中对数组和数据进行排序?

php - 将 MySQL 连接到 Dropbox

woocommerce - 如果产品已添加到 WooCommerce 中的购物车,如何重命名“添加到购物车”按钮

wordpress - 从 Woocommerce 中的单个产品页面中删除产品尺寸