如何使用编程代码动态生成woocommerce优惠券代码 [英] How to generate woocommerce coupon code dynamically using programming code

查看:209
本文介绍了如何使用编程代码动态生成woocommerce优惠券代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态生成woocommerce优惠券代码.

I want to generate woocommerce coupon code dynamically.

我的要求是,完成订单后,会自动在管理端woocommerce优惠券代码列表中为特定产品生成一个优惠券代码.

My requirements is that after complete the order automatically generate one coupon code in admin side woocommerce coupon code list for particular product.

所以任何人都知道我上述要求的解决方案,那么请帮助我.

So any one know my above requirement solutions then please help me.

谢谢, Ketan.

推荐答案

您可以使用woocommerce_order_status_completed操作挂钩来完成订单.并使用wp_insert_post为coupan创建帖子类型为shop_coupon的帖子.检查以下代码

You can used woocommerce_order_status_completed action hook for order complete. and create post with post type shop_coupon for coupan using wp_insert_post. check below code

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

这篇关于如何使用编程代码动态生成woocommerce优惠券代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆