Introduction to WooCommerce and WC_Product()
WooCommerce is a very popular e-commerce platform that allows users to create and manage an online store in a simple and efficient manner. One of the key features of WooCommerce is its ability to handle and manage products effectively. In this article, we will explore product development in WooCommerce using the WC_Product() class, a core class used to create and customize products on the platform.

Creating a basic product with WC_Product()
To create a basic product in WooCommerce using the WC_Product() class, we can follow the PHP code below:
$product = new WC_Product();
$product->set_name('Camiseta');
$product->set_price(20);
$product->set_stock_quantity(50);
$product->save();
In this example, we create a basic product named “T-shirt” with a price of $20 and an initial stock of 50 units. Then, we save the product using the save() method.
Customizing product attributes
The WC_Product() class also allows us to customize a product's attributes. For example, we can set the size and color of a t-shirt as follows:
$product->set_attributes(array('size' => 'S', 'color' => 'blue'));
In this case, we set the product's ‘size’ and ‘color’ attributes to ‘S’ and ‘blue’, respectively. Then, we save the changes using the save() method.
Querying and updating product information
Once we have created a product, we can also query and update its information using specific methods. For example, to obtain the ID, name, price, and stock quantity of a product, we can use the following methods:
$product_id = $product->get_id();
These methods allow us to access and modify the product's information as needed.
Assigning categories and tags to the product
In WooCommerce, it is possible to assign categories and tags to a product to organize and classify them more effectively. Using the WC_Product() class, we can assign categories and tags to a product as follows:
$product->set_category_ids(array(8, 12));
In this example, we assign categories with IDs 8 and 12, and tags with IDs 5 and 9 to the product. Then, we save the changes using the save() method.
Adding images to the product
An important part of presenting a product online is the inclusion of images. In WooCommerce, we can add images to a product using the WC_Product() class. For example:
$product->set_image_id(15);
In this case, we set the main image ID to 15, and the gallery image IDs to 16 and 17. After adding the images, we save the changes using the save() method.
Configuring shipping and tax options
In addition to basic product information, we can also configure shipping and tax options using the WC_Product() class. For example, we can assign a specific shipping class and a reduced tax class as follows:
$product->set_shipping_class_id(3);
In this example, we assign the shipping class with ID 3 and the tax class ‘reduced-rate’ to the product. Then, we save the changes using the save() method.
Linking related products
Occasionally, it can be useful to link related products together to promote additional purchases. Using the WC_Product() class, we can set up-sells and cross-sells as follows:
$product->set_upsells(array(22, 23));
In this case, we set the up-sells with IDs 22 and 23, and the cross-sells with IDs 30 and 31. After establishing the relationships, we save the changes using the save() method.
Managing prices and discounts
The WC_Product() class also allows us to manage prices and discounts for a product in WooCommerce. For example, we can set a regular price, a sale price, and the start and end dates of the offer as follows:
$product->set_regular_price(25);
In this example, we set a regular price of $25, a sale price of $20, and the start and end dates of the offer (from January 1, 2022, to January 31, 2022). Then, we save the changes using the save() method.
Deleting a product
If we need to delete a product from WooCommerce using the WC_Product() class, we can do so using the following code:
$product->delete(true);
In this case, we delete the product and all its related data, such as images, attributes, and relationships. The parameter ‘true’ indicates that all data associated with the product should be deleted.
Complete Code Example
/**
* Crea y gestiona un producto en WooCommerce.
*
* Esta función utiliza la clase WC_Product para crear un nuevo producto en WooCommerce,
* establecer sus propiedades, y finalmente eliminarlo. Se engancha a WordPress para
* ejecutarse en un momento específico.
*
* @return void
*/
function crear_y_gestionar_producto_wc() {
// Crear un nuevo producto
$product = new WC_Product();
$product->set_name('Camiseta'); // Establecer el nombre del producto
$product->set_price(20); // Establecer el precio del producto
$product->set_regular_price(25); // Establecer el precio regular
$product->set_sale_price(20); // Establecer el precio de oferta
$product->set_date_on_sale_from('2022-01-01'); // Fecha de inicio de la oferta
$product->set_date_on_sale_to('2022-01-31'); // Fecha de fin de la oferta
$product->set_stock_quantity(50); // Cantidad de stock
$product->set_manage_stock(true); // Habilitar gestión de stock
$product->set_attributes(array('size' => 'S', 'color' => 'blue')); // Establecer atributos
$product->set_category_ids(array(8, 12)); // Asignar categorías por ID
$product->set_tag_ids(array(5, 9)); // Asignar etiquetas por ID
$product->set_image_id(15); // Asignar ID de la imagen principal
$product->set_gallery_image_ids(array(16, 17)); // Asignar IDs de imágenes de la galería
$product->set_shipping_class_id(3); // Asignar clase de envío por ID
$product->set_tax_class('reduced-rate'); // Asignar clase de impuesto
$product->set_upsells(array(22, 23)); // Establecer productos relacionados por ID
$product->set_cross_sells(array(30, 31)); // Establecer productos complementarios por ID
$product->save(); // Guardar el producto
// Consultar información del producto
$product_id = $product->get_id(); // Obtener el ID del producto
$product_name = $product->get_name(); // Obtener el nombre del producto
$product_price = $product->get_price(); // Obtener el precio del producto
$product_stock = $product->get_stock_quantity(); // Obtener la cantidad de stock
// Actualizar información del producto (ejemplo: cambiar el precio)
$product->set_price(22); // Cambiar el precio del producto
$product->save(); // Guardar los cambios
// Eliminar un producto
// $product->delete(true); // Descomentar para eliminar el producto y sus datos relacionados
}
// Hook para integrar la función con WordPress
// Este ejemplo utiliza 'init', pero puedes cambiarlo según tus necesidades
add_action('init', 'crear_y_gestionar_producto_wc');
In this code:
- Function
crear_y_gestionar_producto_wc: This function is responsible for creating and managing a product in WooCommerce. It uses various methods of theWC_Productclass to set product properties, such as name, price, stock, attributes, categories, images, and more. - Hook
add_action: Integrates the function with WordPress. In this case, theinit, hook is used, which fires after WordPress has finished loading but before any headers are sent. You can change this hook to another one that better suits your needs. - PHPDoc format comments: Each line of code has an explanatory comment to better understand what it does. The PHPDoc comments are in Spanish and provide a clear description of the function and its components.
Note that this code assumes WooCommerce is installed and active on your WordPress site. Additionally, the IDs for categories, tags, images, and shipping classes must be valid in your WooCommerce installation. Also, the line to delete the product is commented out to prevent accidental deletions; you can uncomment it if you need to use that functionality.
Conclusions
In this article, we have explored product development in WooCommerce using the WC_Product() class. We have learned how to create a basic product, customize its attributes, query and update its information, assign categories and tags, add images, configure shipping and tax options, link related products, manage prices and discounts, and delete products. This knowledge provides us with a solid foundation for developing and managing products in WooCommerce effectively. In the next stage of development, we can delve into more advanced concepts and further explore the capabilities of the WC_Product() class.
References and additional resources
- Official WooCommerce documentation: https://docs.woocommerce.com/
- WC_Product() class in the documentation: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html
Do you need help with a web project?
Do you need help with a web project? Don't hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let's talk about your web project!
