Search code examples
phpwordpresswoocommercewordpress-hook

How to get woocommerce product all details when publish a new product?


I want to fetch woocommerce product post data when we publish a new product. I've tried some hooks but it's working only when we update the product. Does anyone knows how can I get the product post data when adding new product?

Here is my code.

add_action( 'save_post_product',  'add_product_tocrm_through_woocommerce', 10, 3);
function add_product_tocrm_through_woocommerce($post_id, $post, $update){

    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }

    if (!$product = wc_get_product( $post )) {
        return;
    }

    $post_type = get_post_type( $post_id );
    $post_status = get_post_status();

    if ( $post_type == 'product' && $post_status == 'publish') {

        $product = wc_get_product($post_id);
        $pNameWoo =   $product->name;
        $price = $product->get_price();
        $desc =  $product->get_description();

        $wooProduct[0]['name'] = $pNameWoo;
        $wooProduct[0]['price'] = $price;
        $wooProduct[0]['description'] = $desc;
        save_woo_product_tocrm($wooProduct);
    }

}

Solution

  • here is the solution using woocommerce_process_product_meta hook.

    add_action( 'woocommerce_process_product_meta', 'add_product_tocrm_through_woocommerce', 99, 2);
    if (!function_exists('add_product_tocrm_through_woocommerce')) {
        function add_product_tocrm_through_woocommerce($product_id, $update)
        {
            $post_type = get_post_type( $product_id );
            $post_status = get_post_status($product_id);
    
            if ($post_status == 'publish' && !$update) {
                $product = wc_get_product($product_id);
                print_r($product);
                $pNameWoo =   $product->get_name();
                $desc =  $product->get_description();
                $price =  $product->get_regular_price();
                $sale_price =  $product->get_sale_price();
                
                $wooProduct['name'] = $pNameWoo;
                $wooProduct['price'] = $price;
                $wooProduct['sale_price'] = $sale_price;
                $wooProduct['description'] = $desc;
                $wooProduct['pid'] = $product_id;
                save_woo_product_tocrm($wooProduct);
            }
        }
    }