WooCommerce: Create Product Programmatically

No matter if this snippet suits your needs or not, it’s still interesting to see how you can create a brand new WooCommerce product programmatically / automatically when a certain even triggers.

In this case studio, we’ll see how to generate a brand new product, set its featured image, price, category, title and a download file as soon as an image is uploaded in the WordPress backend Media section. This would be super useful for photographers for example – simply upload a new image to the WordPress Media Library, and a new product is automatically created.

Of course, you can customize the code and use it with different triggers. For example, you may need to create a new product automatically when each phone product needs always a matching case product, just with a different title. Or maybe you want to tie product creation once an order is placed.

Either way, enjoy!

This product was created automatically, after uploading Calm.jpg to the WordPress Media Library. You find more screenshots below.

PHP Snippet 1: Create Simple Virtual Downloadable Product Automatically When A New Image Is Uploaded @ WordPress Media Library

/**
 * @snippet       AutoCreate Simple Product @ WP Admin
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

add_action( 'add_attachment', 'bbloomer_create_simple_product_automatically', 9999 );

function bbloomer_create_simple_product_automatically( $image_id ) { 
    $product = new WC_Product_Simple();
    $product->set_name( 'Photo: ' . get_the_title( $image_id ) );
    $product->set_status( 'publish' ); 
    $product->set_catalog_visibility( 'visible' );
    $product->set_category_ids( array( 20 ) );
    $product->set_price( 19.99 );
    $product->set_regular_price( 19.99 );
    $product->set_sold_individually( true );
    $product->set_image_id( $image_id );
    $product->set_downloadable( true );
    $product->set_virtual( true );		
    $src_img = wp_get_attachment_image_src( $image_id, 'full' );
    $file_url = reset( $src_img );
    $file_md5 = md5( $file_url );
    $download = new WC_Product_Download();
    $download->set_name( get_the_title( $image_id ) );
    $download->set_id( $file_md5 );
    $download->set_file( $file_url );
    $downloads[$file_md5] = $download;
    $product->set_downloads( $downloads );
	 $product->save();
}

PHP Snippet 2: Create Variable Product Automatically When A New Image Is Uploaded @ WordPress Media Library

/**
 * @snippet       AutoCreate Variable Product @ WP Admin
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

add_action( 'add_attachment', 'bbloomer_create_variable_product_automatically', 9999 );

function bbloomer_create_variable_product_automatically( $image_id ) {
 
    $product = new WC_Product_Variable();
    $product->set_name( 'Photo: ' . get_the_title( $image_id ) );
    $product->set_status( 'publish' ); 
    $product->set_catalog_visibility( 'visible' );
    $product->set_image_id( $image_id );
    $product->set_category_ids( array( 20 ) );

    $attribute = new WC_Product_Attribute();
	 $attribute->set_id( wc_attribute_taxonomy_id_by_name( 'pa_color' ) );
	 $attribute->set_name( 'pa_color' );
	 $attribute->set_options( array( 29, 30 ) ); // color att terms
	 $attribute->set_position( 1 );
	 $attribute->set_visible( 1 );
	 $attribute->set_variation( 1 );
	 $attributes[] = $attribute;
	 $product->set_attributes( $attributes );

    $product->save();

    $variation1 = new WC_Product_Variation();
	 $variation1->set_parent_id( $product->get_id() );
	 $variation1->set_attributes( array( 'pa_color' => 'blue' ) );
	 $variation1->set_regular_price( 99.99 );
	 $variation1->save();

    $variation2 = new WC_Product_Variation();
	 $variation2->set_parent_id( $product->get_id() );
	 $variation2->set_attributes( array( 'pa_color' => 'red' ) );
	 $variation2->set_regular_price( 197.99 );
	 $variation2->save();

}

Screenshots

1. Image upload from Media Library (Calm.jpg)

2. Automatic product creation

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Custom Add to Cart URLs – The Ultimate Guide
    In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: Add Second Description @ Product Category Pages
    In terms of SEO, if you’re trying to rank your product category pages, you really need to make the most of the default WooCommerce product category “description” and “thumbnail”. Most themes, if compatible with WooCommerce, will show this content right below the product category name and above products. Nothing new so far. But what if […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

6 thoughts on “WooCommerce: Create Product Programmatically

  1. Hi Rodolfo Melogli,

    Thank you for this useful snippet. I am using 7.4 and its 9/7/22 and this was just perfect for my requirement!

    Heather Lynn

  2. I couldn’t get this to work. I admit I loathe WP and find it completely dyslexic – so I may be biased. But no – unfortunately spent the whole day on this and nothing worked. 9/7/22

  3. Hi, thanks for your post.

    Is there any way to add brand name to a product?

    thanks again

    1. Hi Javier thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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