WooCommerce: Create Product Programmatically

WooCommerce is a powerful e-commerce plugin for WordPress that allows you to sell products and services online. You can create products in WooCommerce using the WordPress admin panel, but sometimes you might want to create products programmatically using PHP code. In this tutorial, we will show you how to create a product programmatically in WooCommerce using PHP.

Step 1: Create a New Product Object The first step is to create a new product object in WooCommerce. We will use the WC_Product class to create a new product.

php
$new_product = new WC_Product();

Step 2: Set the Product Type The next step is to set the product type. WooCommerce supports several product types such as simple, grouped, variable, and external. For this tutorial, we will create a simple product.

php
$new_product->set_type('simple');

Step 3: Set the Product Name and Description Now we need to set the product name and description. You can set these values using the set_name() and set_description() methods.

php
$new_product->set_name('My Product Name');
$new_product->set_description('My Product Description');

Step 4: Set the Product Price The next step is to set the product price. You can set the product price using the set_regular_price() method.

php
$new_product->set_regular_price(10.99);

Step 5: Set the Product Stock Status and Quantity Now we need to set the product stock status and quantity. You can set the stock status using the set_manage_stock() method and the quantity using the set_stock_quantity() method.

php
$new_product->set_manage_stock(true);
$new_product->set_stock_quantity(100);

Step 6: Set the Product Categories and Tags Now we need to set the product categories and tags. You can set the categories and tags using the set_category_ids() and set_tag_ids() methods.

php
$new_product->set_category_ids(array(1,2));
$new_product->set_tag_ids(array(3,4));

Step 7: Save the Product Finally, we need to save the product using the save() method.

php
$new_product->save();

The complete code to create a product programmatically in WooCommerce is shown below:

php
$new_product = new WC_Product();
$new_product->set_type('simple');
$new_product->set_name('My Product Name');
$new_product->set_description('My Product Description');
$new_product->set_regular_price(10.99);
$new_product->set_manage_stock(true);
$new_product->set_stock_quantity(100);
$new_product->set_category_ids(array(1,2));
$new_product->set_tag_ids(array(3,4));
$new_product->save();

That’s it! You have successfully created a product programmatically in WooCommerce using PHP code. You can modify this code to create products with additional product attributes, such as product images, product variations, and custom product fields.