简体   繁体   中英

Get recently added product using woocommerce hook

I want send an API request after adding the product from Woocommerce admin. Actually what I want is that when user adds a new product (A course) to his shop, and API request will create a course with same name as that of product in the LMS.

I have succeeded to hook product creation event but dont know how to get data of the product that I created or added in woocommerce.

Here is my code:

add_action('transition_post_status', 'product_add', 10, 3);
 function product_add($new_status, $old_status, $post) {
 if( 
        $old_status != 'publish' 
        && $new_status == 'publish' 
        && !empty($post->ID) 
        && in_array( $post->post_type, 
            array( 'product') 
            )
        ) {
            //here I want to get the data of product that is added 
          }
 }

this code is working fine, when I add a product and echo something inside this function it works fine.

Just want to get the Name and Id of the product.

Thanks.

At this point, it's very easy to get any related data to your published product and even more to just get the product ID and the product name. You will find below most of all the possibilities that you have to get any related data from your product:

add_action('transition_post_status', 'action_product_add', 10, 3);
function action_product_add( $new_status, $old_status, $post ){
    if( 'publish' != $old_status && 'publish' != $new_status 
        && !empty($post->ID) && in_array( $post->post_type, array('product') ) ){

        // You can access to the post meta data directly
        $sku = get_post_meta( $post->ID, '_sku', true);

        // Or Get an instance of the product object (see below)
        $product = wc_get_product($post->ID);

        // Then you can use all WC_Product class and sub classes methods
        $price = $product->get_price(); // Get the product price

        // 1°) Get the product ID (You have it already)
        $product_id = $post->ID;
        // Or (compatibility with WC +3)
        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

        // 2°) To get the name (the title)
        $name = $post->post_title;
        // Or
        $name = $product->get_title( );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Everything is tested and works.


Reference: Class WC_Product methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM