2017-03-02 2 views
3

Woocommerceの管理者から商品を追加した後にAPIリクエストを送信します。実際に私が望むのは、ユーザーが自分のショップに新しい製品(Aコース)を追加し、APIリクエストがLMSの製品と同じ名前のコースを作成するということです。woocommerceのフックを使用して最近追加された商品を取得する

私は製品の作成イベントをフックするのに成功しましたが、私が作成した、またはwoocommerceで追加した製品のデータを取得する方法はわかりません。私は、この関数の内部で何かを、製品を追加し、エコーときに、このコードは、正常に動作している

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 
      } 
} 

それが正常に動作します:

は、ここに私のコードです。

商品の名前とIDを取得したいだけです。

ありがとうございました。

答えて

1

この時点では、公開された製品に関連するデータを取得するのは非常に簡単で、さらに製品IDと製品名を取得するだけです。すべてのプラグインファイルでも

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(); 
    } 
} 

コードは、あなたのアクティブな子テーマ(またはテーマ)のfunction.phpファイルに行くか:あなたは、あなたの製品からすべての関連データを取得する必要があり、すべての可能性の最も下にあります。

すべてがテストされ、動作します。


参考:Class WC_Product methods

関連する問題