WC_Abstract_Order::add_product( WC_Product $product, int $qty = 1, array $args = array() )
Add a product line item to the order. This is the only line item type with its own method because it saves looking up order amounts (costs are added up for you).
Description Description
Parameters Parameters
- $product
-
(Required) Product object.
- $qty
-
(Optional) Quantity to add.
Default value: 1
- $args
-
(Optional) Args for the added product.
Default value: array()
Return Return
(int)
Source Source
File: includes/abstracts/abstract-wc-order.php
public function add_product( $product, $qty = 1, $args = array() ) { if ( $product ) { $default_args = array( 'name' => $product->get_name(), 'tax_class' => $product->get_tax_class(), 'product_id' => $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id(), 'variation_id' => $product->is_type( 'variation' ) ? $product->get_id() : 0, 'variation' => $product->is_type( 'variation' ) ? $product->get_attributes() : array(), 'subtotal' => wc_get_price_excluding_tax( $product, array( 'qty' => $qty ) ), 'total' => wc_get_price_excluding_tax( $product, array( 'qty' => $qty ) ), 'quantity' => $qty, ); } else { $default_args = array( 'quantity' => $qty, ); } $args = wp_parse_args( $args, $default_args ); // BW compatibility with old args. if ( isset( $args['totals'] ) ) { foreach ( $args['totals'] as $key => $value ) { if ( 'tax' === $key ) { $args['total_tax'] = $value; } elseif ( 'tax_data' === $key ) { $args['taxes'] = $value; } else { $args[ $key ] = $value; } } } $item = new WC_Order_Item_Product(); $item->set_props( $args ); $item->set_backorder_meta(); $item->set_order_id( $this->get_id() ); $item->save(); $this->add_item( $item ); wc_do_deprecated_action( 'woocommerce_order_add_product', array( $this->get_id(), $item->get_id(), $product, $qty, $args ), '3.0', 'woocommerce_new_order_item action instead' ); delete_transient( 'wc_order_' . $this->get_id() . '_needs_processing' ); return $item->get_id(); }