2017-10-12 27 views
1

私は、動的にクーポンのクーポンコードを生成したいと思います。プログラミングコードを使用して動的にクーポンコードを生成する方法

私の要件は、注文が完了した後、特定の製品の管理サイドのwoocommerceクーポンコードリストに1つのクーポンコードを自動的に生成することです。

だから誰でも私の上記の要件の解決策を知っているので、私を助けてください。

ありがとう、 Ketan。

答えて

1

注文完了のためにwoocommerce_order_status_completedアクションフックを使用できます。 wp_insert_postを使用してクーポンのポストタイプshop_couponのポストを作成します。以下のコードを確認してください

function action_woocommerce_order_status_completed($order_id) { 

    $order = wc_get_order($order_id); 

    $order_items = $order->get_items(); 
    // Iterating through each item in the order 
    $item_quantity=0; 
    foreach ($order_items as $item_id => $item_data) { 

     $item_quantity=$order->get_item_meta($item_id, '_qty', true); 
     if($item_quantity>1){ 
      $product_ids[]=$item_data['product_id']; 
      $coupon_code = 'UNIQUECODE'.$order_id.$item_id; // Code 
      $amount = '10'; // Amount 
      $discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product 

      $coupon = array(
       'post_title' => $coupon_code, 
       'post_content' => '', 
       'post_status' => 'publish', 
       'post_author' => 1, 
       'post_type'  => 'shop_coupon' 
      ); 

      $new_coupon_id = wp_insert_post($coupon); 

      // Add meta 
      update_post_meta($new_coupon_id, 'discount_type', $discount_type); 
      update_post_meta($new_coupon_id, 'coupon_amount', $amount); 
      update_post_meta($new_coupon_id, 'individual_use', 'no'); 
      update_post_meta($new_coupon_id, 'product_ids',$product_ids); 
      update_post_meta($new_coupon_id, 'exclude_product_ids', ''); 
      update_post_meta($new_coupon_id, 'usage_limit', ''); 
      update_post_meta($new_coupon_id, 'expiry_date', ''); 
      update_post_meta($new_coupon_id, 'apply_before_tax', 'yes'); 
      update_post_meta($new_coupon_id, 'free_shipping', 'no'); 
      unset($product_ids); 
     } 

    } 



}; 
// add the action 
add_action('woocommerce_order_status_completed', 'action_woocommerce_order_status_completed', 10, 1); 
+0

ありがとうございます。 私はあなたの解決策を試し、あなたをアップデートします。 ありがとうございます。 – Ketan

+0

こんにちはAnkur、 私のfunctions.phpファイルに上記のコードを追加した後、フロントエンドとバックエンドの両方に白い空白の画面が表示されます。 上記のコードを確認して、ここで私に連絡してください。 ありがとうございます。 – Ketan

+0

$ coupon_code = 'UNIQUECODE' $ order_id;この行のエラー。 UNIQUECODEと$ order_idの間に '.'を付けてください。編集した回答を確認してください –

0

woocommerce_order_status_completedまたはwoocommerce_order_status_processingフックを使用して注文が完了または発注されたときに起動する機能を作成します。関数内でwp_insert_postを使用して、shop_coupon型の投稿を作成します。 wp_insert_postを使用して、クーポンのタイトル、金額などを指定できます。

+0

ありがとうございました。 私はあなたの解決策を試し、あなたをアップデートします。 ありがとうございます。 – Ketan

関連する問題