How to use add_product function for variations in Woocommerce

I am trying to add product variations using the add_product() function from woocommerce.

But everytime I add the variation product. It just adds the parent product and not the variation.

Read More
$product_id = 40;
$variation_id = 42;
$quantity = 1;
$variation_name = color;
$variation_option = red;

$args = array(
    'attribute_'.$variation_name => $variation_option,
);

$order = wc_create_order();
$order->add_product( get_product( $product_id ), $quantity, $args );

I also have tried this which also doesn’t work

$order->add_product( get_product( $variation_id ), $quantity, $args );

I have doubled checked the variation id, attribute, name and option.

Related posts

Leave a Reply

2 comments

  1. I think something wrong pass args parameter try this

    $product_id = 132;
    $quantity = 1;
    
    $args = array( 
     'variation' => array( 'attribute_color' => 'red'),
    ); 
    
    $order = wc_create_order();
    $order->add_product( get_product( $product_id ), $quantity, $args );
    //$order->set_total( 15.50 ); // set total amount for paid order including tax, fees etc. 
    
  2. Edited in 2022

    1 – The get_product() function is deprecated and the wc_get_product()function should be used.

    2 – To calculate the final price, calculate_totals() function should be used to set the paid price.

    UPDATE CODE :

    Create a manual WooCommerce order:

    $args = array(
        'status' => 'wc-completed', // The type of product status is up to you
        'customer_id' => 1, // user ID
        'customer_note' => null,
        'parent' => null,
        'created_via' => null,
        'cart_hash' => null,
    );
    $order = wc_create_order($args);
    

    and set a desired product to order.

    And we use the function wc_downloadable_product_permissions() to set the access of product download files.

    $product_id = 100;
    $quantity = 1;
    $args = array(
        'name' => "",
        'tax_class' => "",
        'product_id' => 100,
        'variation_id' => "",
        'variation' => "",
        'subtotal' => 0,
        'total' => 0, // If you want the price of the selected product, remove it
        'quantity' => 1,
    );
    
    $order->add_product( wc_get_product( $product_id ), $quantity, $args );
    
    $order->calculate_totals(); // To calculate the final price paid
    
    wc_downloadable_product_permissions($order->get_id(), true); //Set product download access for order