---
description: https://www.businessbloomer.com/woocommerce-programmatically-create-product/
---

# Create Product Automatically When A New Image Is Uploaded (ok)

**Đọc thêm cái này để biết chi tiết**

[https://rudrastyh.com/woocommerce/create-product-programmatically.html](https://rudrastyh.com/woocommerce/create-product-programmatically.html)

C:\xampp\htdocs\style2\wp-content\themes\twentytwentyone\functions.php

```
add_action( 'add_attachment', 'bbloomer_create_product_automatically', 9999 );
function bbloomer_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();
}
```

![](https://1113999984-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M84NwP_L_qEsBHOa2xo%2Fuploads%2FHW5pztR3WV4xOKVnIlCo%2FScreenshot_2.png?alt=media\&token=a143dd3a-27b8-4a2c-bc1f-c92bee211380)

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.

![](https://www.businessbloomer.com/wp-content/uploads/2021/10/woocommerce-create-product-programmatically-1024x577.png)

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

### Screenshots

```
/**
 * @snippet       AutoCreate Product @ WP Admin
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'add_attachment', 'bbloomer_create_product_automatically', 9999 );
 
function bbloomer_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();
}
```

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

![](https://www.businessbloomer.com/wp-content/uploads/2021/10/image-1024x556.png)

#### 2. Automatic product creation

\


![](https://www.businessbloomer.com/wp-content/uploads/2021/10/image-2-1024x498.png)

![](https://www.businessbloomer.com/wp-content/uploads/2021/10/image-1-1024x498.png)

## [`Đọc thêm`](https://rudrastyh.com/woocommerce/create-product-programmatically.html)

## Create Products Programmatically

Updated on May 7, 2022

In this tutorial I am going to guide you through the process of creating products in WooCommerce in code.

It is the most correct way of creating products in latest WooCommerce versions. So, please forget about `wp_insert_post()` and `update_post_meta()` functions. Yes, I perfectly remember that products are WordPress custom post types and product prices are post meta but it doesn’t allow us to use those functions anyway, because there is a little more than that and it could cause bugs.

In this tutorial we are going to use CRUD objects that were introduced in WooCommerce 3.0 (CRUD is an abbreviation of Create, Read, Update, Delete). The CRUD objects we are interested in right now are:

* `WC_Product_Simple` – for simple products,
* `WC_Product_External` – for external products,
* `WC_Product_Grouped` – for grouped products,
* `WC_Product_Variable` – variable ones.

We are also going to use plenty of methods of these objects, that allow us to configure our product data.

### Simple Products  <a href="#simple-products" id="simple-products"></a>

Let’s start with creating a simple product. I am suggesting you to imagine, what a dead simple product should have? Well, it starts with product name, slug (for URL), price and.. image, right? Okay, we may have some product description with its benefits as well!

```php
// that's CRUD object
$product = new WC_Product_Simple();

$product->set_name( 'Wizard Hat' ); // product title

$product->set_slug( 'medium-size-wizard-hat-in-new-york' );

$product->set_regular_price( 500.00 ); // in current shop currency

$product->set_short_description( '<p>Here it is... A WIZARD HAT!</p><p>Only here and now.</p>' );
// you can also add a full product description
// $product->set_description( 'long description here...' );

$product->set_image_id( 90 );

// let's suppose that our 'Accessories' category has ID = 19 
$product->set_category_ids( array( 19 ) );
// you can also use $product->set_tag_ids() for tags, brands etc

$product->save();
```

The code above is enough to create a product like this.

![Create a Simple WooCommerce product programmatically](https://rudrastyh.com/wp-content/uploads/2022/05/create-simple-product-programmatically.png)Newly created product, Storefront theme.

There are also methods that you could find useful:

* `set_featured()` – pass `true` if you want this product to be marked as featured.
* `set_gallery_image_ids()` – multiple image IDs can be passed as an array here.
* `set_menu_order()` – manual product order as an integer.
* `set_status()` – any post status here. Don’t want the product to be published? Set `draft` here.
* `set_total_sales()` – product total sales can be passed here as an integer value.
* `set_catalog_visibility()` – visibility in the catalog can be configured with this method, `hidden`, `visible`, `search` and `catalog` values are accepted.
* `update_meta_data()` – any product meta data, pass a pair of meta key and meta value as first and second parameters appropriately.

#### Products on Sale  <a href="#on-sale-products" id="on-sale-products"></a>

You can use it in combination with [the snippet above](https://rudrastyh.com/woocommerce/create-product-programmatically.html#simple-products), but please don’t forget to add these methods before `$product->save();` line.

```php
$product->set_regular_price( 500.00 );
$product->set_sale_price( 250.00 );
// sale schedule
$product->set_date_on_sale_from( '2022-05-01' );
$product->set_date_on_sale_to( '2022-05-31' );
```

The product price has been changed and depending on a theme you’re using Sale! could appear, by the way there is a different tutorial on [how to remove or modify it](https://rudrastyh.com/woocommerce/change-or-remove-sale-badge.html).

![](https://rudrastyh.com/wp-content/uploads/2022/05/woocommerce-create-onsale-product-programmatically.png)

#### Inventory Settings  <a href="#inventory" id="inventory"></a>

```php
$product->set_sku( 'wzrd-hat' ); // Should be unique

// You do not need it if you manage stock at product level (below)
$product->set_stock_status( 'instock' ); // 'instock', 'outofstock' or 'onbackorder'

// Stock management at product level
$product->set_manage_stock( true );
$product->set_stock_quantity( 5 );
$product->set_backorders( 'no' ); // 'yes', 'no' or 'notify'
$prodict->set_low_stock_amount( 2 );

$product->set_sold_individually( true );
```

The parameters above lead to this Inventory configuration.

![product inventory settings while creating a product in code](https://rudrastyh.com/wp-content/uploads/2022/05/woocommerce-product-inventory-settings.png)

#### Dimensions and Shipping  <a href="#dimensions-and-shipping" id="dimensions-and-shipping"></a>

```php
$product->set_weight( 0.5 );
$product->set_length( 50 );
$product->set_width( 50 );
$product->set_height( 30 );

$product->set_shipping_class_id( 'hats-shipping' );
```

In case you’re wondering what is a shipping class ID and where you can get it, I recommend you to [check this tutorial](https://rudrastyh.com/woocommerce/how-to-get-shipping-class-id.html).

#### Linked Products  <a href="#linked-products" id="linked-products"></a>

There are two methods – `set_upsell_ids()` and `set_cross_sell_ids()`, both of them accept an array of product IDs.

```php
$product->set_upsell_ids( array( 15, 17 ) );

// we can do the same for cross-sells
// $product->set_cross_sell_ids( array( 15, 17, 19, 210 ) );
```

![WooCommerce product upsells](https://rudrastyh.com/wp-content/uploads/2022/05/woocommerce-product-upsells.png)

#### Attributes  <a href="#attributes" id="attributes"></a>

This is going to be interesting.

First of all I want to remind you that there are two types of product attributes in WooCommerce – predefined taxonomy-based attributes (can be created in **Products > Attributes**) and individual product attributes.

Second, forget about `wp_set_object_terms()` here.

No matter what type of attribute you are going to add to a product, you have to use the single method which is `set_attributes()`. But what should we pass into it? Below is the example of how to use `WC_Product_Attribute` class in order to add a custom or taxonomy-based attribute to a product programmatically.

```php
// that's going to be an array of attributes we add to a product programmatically
$attributes = array();

// add the first attribute
$attribute = new WC_Product_Attribute();
$attribute->set_name( 'Magical' );
$attribute->set_options( array( 'Yes', 'No' ) );
$attribute->set_position( 0 );
$attribute->set_visible( true );
$attribute->set_variation( true );
$attributes[] = $attribute;

// add the second attribute, it is predefined taxonomy-based attribute
$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, 31 ) );
$attribute->set_position( 1 );
$attribute->set_visible( true );
$attribute->set_variation( false );
$attributes[] = $attribute;

$product->set_attributes( $attributes );
```

When creating attributes you have to remember two things:

* The difference between creating custom or taxonomy-based attributes is in what you pass into `set_id()` and `set_name()` methods. It should be an attribute taxonomy name inside `wc_attribute_taxonomy_id_by_name()` function and just a taxonomy name appropriately.
* When you pass term IDs in `set_option()` function, **you shouldn’t do it too early** in the code when taxonomy is not even registered. It also applies to product categories and tags.

![Create product attributes WC\_Product\_Attribute in code](https://rudrastyh.com/wp-content/uploads/2022/05/create-product-attributes-programmatically.gif)

#### Virtual and Downloadable products  <a href="#virtual-and-downloadable" id="virtual-and-downloadable"></a>

Let’s assume that our Wizard Hat is just an illustration that we are going to purchase or an accessory in a game like Lineage II. How to make it virtual and downloadable as well?

It is kind of similar how we made it [for product attributes](https://rudrastyh.com/woocommerce/create-product-programmatically.html#attributes).

```php
// Virtual product : YES
$product->set_virtual( true );
// Downloadable product : YES
$product->set_downloadable( true );

$downloads = array();

// Creating a download with... yes, WC_Product_Download class
$download = new WC_Product_Download();
$file_url = wp_get_attachment_url( $attachment_id ); // attachmend ID should be here
$download->set_name( 'wizard-hat-illustration' );
$download->set_id( md5( $file_url ) );
$download->set_file( $file_url );

$downloads[] = $download;

$product->set_downloads( $downloads );

$product->set_download_limit( 1 ); // can be downloaded only once
$product->set_download_expiry( 7 ); // expires in a week
```

![how to create virtual and downloadable products](https://rudrastyh.com/wp-content/uploads/2022/05/create-virtual-downloadable-products.png)

### External and Grouped products  <a href="#external-and-grouped-products" id="external-and-grouped-products"></a>

Creating both external and grouped products programmatically are quite simple. If you read [the previous chapter](https://rudrastyh.com/woocommerce/create-product-programmatically.html#simple-products) carefully, you won’t have any problems with it at all.

First of all you have to choose an appropriate product PHP-class, which is `WC_Product_External` for external products and `WC_Product_Grouped` for grouped ones.

Then you have to use `set_button_text()` and `set_product_url()` methods to add a link to a partner website where this external product is actually listed. For grouped products you have to use `set_children()` method only.

### Variable Products  <a href="#variable-products" id="variable-products"></a>

Well, it is going to be interesting again. But as always we will make it as simple as possible.

```php
// Creating a variable product
$product = new WC_Product_Variable();

// Name and image would be enough
$product->set_name( 'Wizard Hat' );
$product->set_image_id( 90 );

// one available for variation attribute
$attribute = new WC_Product_Attribute();
$attribute->set_name( 'Magical' );
$attribute->set_options( array( 'Yes', 'No' ) );
$attribute->set_position( 0 );
$attribute->set_visible( true );
$attribute->set_variation( true ); // here it is
	
$product->set_attributes( array( $attribute ) );

// save the changes and go on
$product->save();

// now we need two variations for Magical and Non-magical Wizard hat
$variation = new WC_Product_Variation();
$variation->set_parent_id( $product->get_id() );
$variation->set_attributes( array( 'magical' => 'Yes' ) );
$variation->set_regular_price( 1000000 ); // yep, magic hat is quite expensive
$variation->save();

$variation = new WC_Product_Variation();
$variation->set_parent_id( $product->get_id() );
$variation->set_attributes( array( 'magical' => 'No' ) );
$variation->set_regular_price( 500 );
$variation->save();
```

Of course, `WC_Product_Variation` class has much more methods, almost like `WC_Product_Simple`, all of them you could find in official WooCommerce documentation.

But for now – we have this simple variable product in our shop.

![](https://rudrastyh.com/wp-content/uploads/2022/05/create-variable-product-programmatically.gif)

Almost forgot, you can set a default variation with `set_default_attributes()` method.

```php
$product->set_default_attributes( array( 'magical' => 'No' ) );
```

\# [WooCommerce](https://rudrastyh.com/category/woocommerce), [Products](https://rudrastyh.com/tag/products)

![Misha Rudrastyh](https://rudrastyh.com/wp-content/themes/mishadigital/assets/misha-rudrastyh.jpg)

#### Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? [Contact me](https://rudrastyh.com/contact)

[Follow me on Twitter](http://twitter.com/rudrastyh)

#### Comments — 3

*   Gerald![](https://secure.gravatar.com/avatar/c0a670b04cfe432634d2255e85bd22a9?s=30\&d=blank\&r=g)May 6, 2022 &#x20;

    Thanks for this awesome guide!\
    I really just used wp\_insert\_post to create Woo Products.\
    Appreciate your sharing!

    [Reply](https://rudrastyh.com/woocommerce/create-product-programmatically.html?replytocom=7531#respond)

    *   Misha![](https://secure.gravatar.com/avatar/cbc2c695ec067908b54236e7b04fc98f?s=30\&d=blank\&r=g)May 6, 2022 &#x20;

        Thanks Gerald!

        I hope `wp_insert_post()` is in the past now! ;)

        [Reply](https://rudrastyh.com/woocommerce/create-product-programmatically.html?replytocom=7532#respond)
*   Léo![](https://secure.gravatar.com/avatar/85cc0267e49a69cb1beb3b291f3b1f9b?s=30\&d=blank\&r=g)Jun 27, 2022 &#x20;

    Thank you very much !

## [Đọc thêm ](https://wp-kama.com/function/wp_insert_post)
