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

counter=1
until [ $counter -gt 15 ]
do
	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 'https://picsum.photos/600/400.jpg' --post_id=$product_id --title="Image for Product ${counter}" --featured_image
	wp post meta set $product_id _price $random_price
	counter=$(($counter + 1))
done

Leave a Reply

Your email address will not be published. Required fields are marked *