Get Item/Product Attribute in WooCommerce Order

I’m trying to get Item or Product Attribute in WooCoomerce Order.

How can I get it?

Read More
$order  = new WC_Order( $order_id );
$items  = $order->get_items();

foreach ( $items as $item ) {
        $pid    = $item['product_id'];
        $patt   = $pid->get_attribute( 'pa_myattrname' );
        echo $patt;
}

Later, I want to insert autoresponder link on attribute, so that after user complete payment, they will automatically subscribed into my autoresponder.

Thank you

Related posts

2 comments

  1. I know that it is old question, but that answer may help someone who is looking for nicer option.
    There is much simpler way to get product attributes from order. You just need to go into products (items) and then load meta data

    // at first get order object
    $order = wc_get_order($orderId);
    
    // iterate through order items/products
    foreach ($order->get_items() as $item) {
      // load meta data - product attributes
      foreach ($item->get_meta_data() as $metaData) {
        $attribute = $metaData->get_data();
    
        // attribute value
        $value = $attribute['value'];
    
        // attribute slug
        $slug = $attribute['key'];
      }
    }
    
  2. $item['product_id']; will return the integer product_id, you cannot call get_attribute method on it. Using the integer product_id you need to create a Product object and then call the method

    $pid = $item['product_id'];  // returns the product id
    
    $p = new WC_Product( $pid );  // create an object of WC_Product class
    
    $patt = $p->get_attribute( 'pa_myattrname' );  // call get_attribute method
    
    echo $patt;
    

Comments are closed.