Ví dụ đơn giản bạn muốn tạomã giảm giá 20% tối đa 50k cho khách hàng thì làm thế nào?

Vấn đề này Woo không có sẵn mà bạn cần thêm 1 đoạn code nhỏ bên dưới vào wp-content/themes/{your-theme}/functions.php là được nhé.

/*
* Cách thêm mức giảm tối đa cho mã giảm giá trong Woocommerce
* Maximum discount with coupon code in Woocommerce
* Fixed & Update by levantoan.com
*/add_action( 'woocommerce_coupon_options', 'devvn_max_discount_woocommerce_coupon_options', 10, 2 );
function devvn_max_discount_woocommerce_coupon_options( $coupon_id, $coupon ){
    // max discount per coupons
    $max_discount =  get_post_meta( $coupon_id, '_max_discount', true );
    woocommerce_wp_text_input( array(
        'id'                => 'max_discount',
        'label'             => __( 'Mức giảm tối đa', 'devvn' ),
        'placeholder'       => esc_attr__( 'Nhập số tiền giảm tối đa', 'devvn' ),
        'description'       => __( 'Mức giảm tối đa mà mã giảm giá này có thể giảm.', 'devvn' ),
        'type'              => 'number',
        'desc_tip'          => true,
        'class'             => 'short',
        'custom_attributes' => array(
            'step'  => 1,
            'min'   => 0,
        ),
        'value' => $max_discount ? $max_discount : '',
    ) );
}
add_action( 'woocommerce_coupon_options_save', 'devvn_max_discount_woocommerce_coupon_options_save', 10, 2 );
function devvn_max_discount_woocommerce_coupon_options_save( $coupon_id, $coupon ) {
    update_post_meta( $coupon_id, '_max_discount', wc_format_decimal( $_POST['max_discount'] ) );
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'devvn_max_discount_woocommerce_coupon_get_discount_amount', 20, 5 );
function devvn_max_discount_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $coupon ) {
    $max_discount = get_post_meta( $coupon->get_id(), '_max_discount', true );
    if ( is_numeric($max_discount) && ! is_null( $cart_item ) && WC()->cart->subtotal_ex_tax ) {
        $cart_item_qty = is_null( $cart_item ) ? 1 : $cart_item['quantity'];
        if ( wc_prices_include_tax() ) {
            $discount_percent = ( wc_get_price_including_tax( $cart_item['data'] ) * $cart_item_qty ) / WC()->cart->subtotal;
        } else {
            $discount_percent = ( wc_get_price_excluding_tax( $cart_item['data'] ) * $cart_item_qty ) / WC()->cart->subtotal_ex_tax;
        }
        $_discount = ( $max_discount * $discount_percent );
        $discount = min( $_discount, $discount );
    }
    return $discount;
}

Sau khi add code xong trong mục thêm mã giảm giá > tabChungsẽ có thêm mục“Mức giảm tối đa”bạn chỉ cần nhập số tiền tối đa có thể giảm vào đó là xong

Categorized in:

Quản trị WP,

Last Update: Tháng 4 25, 2024

Tagged in: