如何使用编程代码动态生成 woocommerce 优惠券代码

How to generate woocommerce coupon code dynamically using programming code

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

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

所以谁知道我上面的需求解决方案,请帮助我。

谢谢, 科坦.

编写一个函数,在使用 woocommerce_order_status_completedwoocommerce_order_status_processing 挂钩完成或下单时触发。在函数内部,使用 wp_insert_post 创建类型 shop_coupon 的 post。使用wp_insert_post,您可以指定优惠券的名称、金额等

您可以使用 woocommerce_order_status_completed 操作挂钩完成订单。并使用 post 创建 post 并使用 wp_insert_post 为 coupan 输入 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 );