Nidhi
Nidhi

Reputation: 63

How to create a variable product using the WC_Product Class of WooCommerce?

I was trying to create the variable product in WooCommerce using WC_Product class. We are successful to create an simple product but not able to create a variable product with the following code:

 $products = new WC_Product();//$wcProductID
   $products->set_name('Test Product Config For True color123');
    $products->set_sku('testconfig_ptttttkkkkkkkkkkkk123');
    $products->set_regular_price(200);   
    $products->set_sale_price(180);
     $products->set_attributes( array('name'=>'Color',
                'slug'=>'color',
                'position'=>'0',
                'visible'=>'true',
                'variation'=>'true',
                'options'=>array('red','black')
            ) );

          ));

   $result=$products->save();

This code is creating the simple product in WooCommerce. We need to create an variable product with option and variation.

    $products->set_variation(array( array(
                    'sku' => 'codered',
                    'regular_price' => '29.98',
                    'attributes' => array( 
                        array( 
                            'name'=>'color',
                            'options'=>'red'
                        )

                    ) 
                ),
                array(
                    'sku' => 'codeblack',
                    'regular_price' => '29.98',
                    'attributes' => array( 
                        array( 
                            'name'=>'color',
                            'options'=>'black'
                        )
                    ) 
                ) 
              ));

Upvotes: 1

Views: 4116

Answers (1)

Janine Kroser
Janine Kroser

Reputation: 444

you can create a variable product like this:

try {
     $new_variable_product = new WC_Product_Variable();
     $new_variable_product->set_name("Testname");
     $new_variable_product->set_sku("Testsku");

     $new_variable_product->save();
 } catch (Exception $ex) {
     /* ERROR LIKE "SKU ALREADY EXISTS" */
     write_error_log($ex->getMessage());
 }

https://docs.woocommerce.com/wc-apidocs/class-WC_Product_Variable.html

A simple product is created like this:

try {
      $new_simple_product = new WC_Product_Simple();
      $new_simple_product->set_name("Testname");
      $new_simple_product->set_sku("Testsku");

      $new_simple_product->save();
} catch (Exception $ex) {
      /* ERROR LIKE "SKU ALREADY EXISTS" */
      write_error_log($ex->getMessage());
}

https://docs.woocommerce.com/wc-apidocs/class-WC_Product_Simple.html

Upvotes: 0

Related Questions