A client needed to add “something” upon product publishing. As you know, for example, post meta information called “total_sales” gets added automatically once a product is created. So, let’s see how to do “stuff” when a new product is published.

Example: let’s add_post_meta when a WooCommerce product is created

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

The PHP solution: do “something” when a product is created


/**
 * @snippet       Do Something When Product is Published
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=543
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.2.6
 */

function add_this_to_new_products( $new_status, $old_status, $post ) {

    global $post;

    if ( $post->post_type !== 'product' ) return;

    if ( 'publish' !== $new_status or 'publish' === $old_status ) return;

    add_post_meta( $post->ID, 'total_amount', '0', true ); // This is the action to take

}

add_action( 'transition_post_status', 'add_this_to_new_products', 10, 3 );

Share:

Leave a Reply