Cogito ergo sum

How to trigger a specific code after a new product is created via WooCommerce REST API2 min read

I ran yesterday into a situation where I needed WordPress to perform a specific action after a product is inserted into WooCommerce database using the REST API endpoint POST /wp-json/wc/v3/products

I have searched online for a couple of hours and I found multiple solutions, but non of them worked in my case. Almost all of them work fine when you add a product from within the WordPress backend (the normal way via WP backend area–> Products–> Add new).
You can use one of the following hooks to trigger whatever you want after creating a product using the normal way:

add_action('added_product_meta', 'my_function', 10, 4 );
add_action('updated_product_meta', 'my_function', 10, 4 );
do_action('rest_insert_product', 'my_function', WP_Post $post, WP_REST_Request $request, bool $creating )
add_action('save_post_product', 'my_function', 10, 3);
add_action('save_post', 'my_function', 10, 3);
add_action('woocommerce_api_create_product', 'my_function', 10, 2 );

The hook that worked in my case was woocommerce_new_product . Place the following code in your theme functions.php file.

    add_action( 'woocommerce_new_product','send_email_after_a_product_is_created' , 10, 2);
    function send_email_after_a_product_is_created( $product_id ) {
    // Don't do anything when we are editing an existing product
    if (wp_is_post_revision($product_id)) 
     if ( get_post_type($product_id ) == 'product' ) 
        $product_title = get_the_title( $product_id );
        $product_url = get_permalink( $product_id );
        $subject = 'New product in your WooCommerce shop';
        $message = "A new product has been added to your webshop with the following title :\n\n";
        $message .= $product_title . ": " . $product_url;
        // Send email
        wp_mail( 'YOUR_EMAIL_ADDRESS@EXAMPLE.COM', $subject, $message );


The above example sends me an email every time a product is created in WooCommerce using the REST API. You can execute whatever code you want instead of sending the email. I have used the email as an example. In my case it wasn’t about sending the email, it was something different which is a bit complex! email received after a product is added in WooCommerceThe email I received after I did a POST request on /wp-json/wc/v3/products !



About the author

Peshmerge Morad

Data Science student and a software engineer whose interests span multiple fields.

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Cogito ergo sum