Home » WooCommerce: Create Product Programmatically

WooCommerce: Create Product Programmatically

by Tutor Aspire

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: Create Product Automatically When A New Image Is Uploaded @ WordPress Media Library

/**
 * @snippet       AutoCreate Product @ WP Admin
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 5
 * @donate $9     https://www.tutoraspire.com
 */

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

function tutoraspire_create_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_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();
}

Screenshots

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

2. Automatic product creation

You may also like