15 1 0 4000 1 https://codeblock.co.za 300 true 0
theme-sticky-logo-alt

add_product()

0 Comments

Framework / CMS

WooCommerce [Version: Since 3.0.0]

Syntax

Typical Usage

Adds a product to a WooCommerce 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).

Accepted Parameters

  • product (WC_Product) (Required): The product object. Also see wc_get_product().
  • qty (integer) (Optional, Default = 1): Quantity to add.
  • args (array) (Optional): An array of arguments for the added product.

Return Value(s)

Returns the ID of the newly added order item.

Notes

Throws an error exception if an item can’t be added to the cart.

Arguments that may be overridden may include any of the following:

  • name
  • tax_class
  • product_id
  • variation_id
  • variation
  • subtotal
  • total
  • quantity

Examples of add_product()

Example 1

<?php
$user_id = get_current_user_id();
$order_args = array(
     'customer_id'   => $user_id,
     'status'        => 'on-hold',
     'customer_note' => 'Your order is on hold.',
     'parent'        => '1234',
     'created_via'   => 'Promotion Page',
     'cart_hash'     => '6516s1fv61asd21f6a5a1vad651d651v651asd',
     'order_id'      => '1234'
);
$new_order = wc_create_order($order_args);

$new_order->add_product( wc_get_product(1234), 2);

The above example will create a new order and uses add_product() to add a product to the order. The first parameter of add_product() uses wc_get_product() to lookup the product by the product ID. The second parameter sets the quantity.

Was This Helpful?

Previous Post
wc_create_order()
Next Post
wc_get_product()

0 Comments

Leave a Reply