wooCommerce: Create product variants with WP-CLI

Icon NetzkollektivBy Dominik Krebs, Managing Director, CTO

Creating product variants using the wooCommerce backend is easy, but for many products not very efficient. When it comes to automate the product creation process either the REST API or WP-CLI can be used. In our scenario WP-CLI was the best bet as we were working on the shell anyway. Instead of using cURL we opted for using WP-CLI directly. WP-CLI, or better WP WC CLI is the wooCommerce part of WP-CLI and offers a rangeful of WC CLI commands.

Creating the variable product with WP-CLI

To create product variants in wooCommerce via WP-CLI on the command line, a variable product must first be created. The product is assigned the attributes that will later be used to create the variations and can be selected by the user on the product detail page. We save the output of the command in a Bash variable $PID. This contains the product ID of the created product (–porcelain) and can be used in the following calls to link the variable product with its variants.

PID=`wp wc product create --name=“Variables Produkt” --slug=variable-product --type=variable --status=1 --sku=variable --regular_price=200 --status=publish --attributes='[
  { "name": "Size", "options" : ["small", "medium", "large"], "visible": true, "variation": true }
]' --porcelain --user=admin`

Creating variant products in wooCommerce with WP-CLI

Each variant is then created individually, whereby the attribute name and the options must be identical to the main product:

wp wc product_variation create $PID --attributes='[{"name":"Size","option":"small"}]' --regular_price=199 --user=admin
wp wc product_variation create $PID --attributes='[{"name":"Size","option":"medium"}]' --regular_price=199 --user=admin
wp wc product_variation create $PID --attributes='[{"name":"Size","option":"large"}]' --regular_price=199 --user=admin

The created product is now visible in the wooCommerce frontend and can be purchased. The variants small, medium and large can be selected.

wooCommerce Agentur gesucht?

Sie sind auf der Suche nach einer zuverlässigen Agentur, die sich mit wooCommerce auskennt und Ihnen unkompliziert durch den Online-Shop Alltag hilft? NETZKOLLEKTIV betreut Händler seit über 10 Jahren. Rufen Sie uns an!

Jetzt unverbindlich über mein Projekt sprechen