How to generate WooCommerce products with the WP CLI

The WP CLI never ceases to impress me. You can do lots of things with just a few lines of code.

In this code snippet, I let the WP CLI create 15 products with random images from Lorem Picsum, prices are also random within the 1-1000 range.

The reason I use Lorem Picsum specifically is that it provides URLs with extension compatible with the WordPress media upload condition, other services don’t have this.

The code

until [ $counter -gt 15 ]
	product_id=$(wp post generate --post_type=product --count=1 --post_title="Product ${counter}" --format=ids)
	random_price=$(shuf -i 1-100 -n 1)
	wp media import '' --post_id=$product_id --title="Image for Product ${counter}" --featured_image
	wp post meta set $product_id _price $random_price
	counter=$(($counter + 1))

Leave a comment

Your email address will not be published.