WC_Abstract_Order::add_product()publicWC 1.0

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).

Метод класса: WC_Abstract_Order{}

Хуков нет.

Возвращает

int.

Использование

$WC_Abstract_Order = new WC_Abstract_Order();
$WC_Abstract_Order->add_product( $product, $qty, $args );
$product(WC_Product) (обязательный)
Product object.
$qty(int)
Quantity to add.
По умолчанию: 1
$args(массив)
Args for the added product.
По умолчанию: array()

Код WC_Abstract_Order::add_product() WC 8.7.0

public function add_product( $product, $qty = 1, $args = array() ) {
	if ( $product ) {
		$order = ArrayUtil::get_value_or_default( $args, 'order' );
		$total = wc_get_price_excluding_tax(
			$product,
			array(
				'qty'   => $qty,
				'order' => $order,
			)
		);

		$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'     => $total,
			'total'        => $total,
			'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 = wc_get_container()->get( LegacyProxy::class )->get_instance_of( WC_Order_Item_Product::class );
	$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();
}