Home » WooCommerce: Do Something When Product is Published

WooCommerce: Do Something When Product is Published

by adminkys

A client needed to add “something” upon product publishing. For example, product meta key “total_sales” with value = 0 gets added automatically once a WooCommerce product is created.

So, how do we run (“hook”) our function when a new product is published?

woocommerce-hook-action-on-product-publish
WooCommerce: add_post_meta on product creation

PHP Snippet: Add Custom Meta When a Product is Published

In here we trigger our function when a product goes from a non-published status (‘draft’, ‘pending’, ‘private’, ‘future’) to ‘publish’ status.

/**
 * @snippet       Hook into product publishing
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 6
 * @donate $9     https://www.tutoraspire.com
 */

add_action( 'transition_post_status', 'tutoraspire_add_custom_meta_on_publish_product', 9999, 3 );

function tutoraspire_add_custom_meta_on_publish_product( $new_status, $old_status, $post ) {
   if ( 'product' === $post->post_type && 'publish' === $new_status && 'publish' !== $old_status ) {
      update_post_meta( $post->ID, 'total_amount', '0' );
   }
}

You may also like