添加 WooCommerce 结帐复选框字段,根据产品数量启用折扣

Add a WooCommerce checkout checkbox field that enable a discount based on product quantity

根据 Add a checkout checkbox field that enable a percentage fee in Woocommerce 答案代码,我有一个自定义复选框,我需要在上面为客户提供折扣。

我正在尝试应用 0.03 美元 x 产品数量的自定义折扣,例如

如果数量为 50,则折扣为 50 x 0.03 美元 = 1.5 美元

现在,它从购物车总计中扣除 0.03 美元。谁能帮我达到要求的结果?

这是我的代码尝试:

// Add a custom checkbox fields after billing fields
add_action( 'woocommerce_after_checkout_billing_form', 'add_custom_checkout_checkbox', 20 );
function add_custom_checkout_checkbox(){

// Add a custom checkbox field
woocommerce_form_field( 'discount30', array(
    'type'  => 'checkbox',
    'label' => __(' Senior'),
    'class' => array( 'form-row-wide' ),
), '' );
}

// Remove "(optional)" label on "Installement checkbox" field
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'discount30' === $key && is_checkout() ) {
    $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . 
')</span>';
    $field = str_replace( $optional, '', $field );
}
return $field;
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :

if( WC()->session->__isset('enable_fee') )
    WC()->session->__unset('enable_fee')
?>
<script type="text/javascript">
jQuery( function($){
    if (typeof wc_checkout_params === 'undefined') 
        return false;

    $('form.checkout').on('change', 'input[name=discount30]', function(e){
        var fee = $(this).prop('checked') === true ? '1' : '';

        $.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: {
                'action': 'enable_fee',
                'enable_fee': fee,
            },
            success: function (result) {
                $('body').trigger('update_checkout');
            },
        });
    });
});
</script>
<?php
endif;
}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
function get_enable_fee() {
if ( isset($_POST['enable_fee']) ) {
    WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
}
die();
}

// Add a custom 3 Cents Discount
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 20, 1 );
function custom_discount( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
    return;

$discount = -0.03;

if( WC()->session->get('enable_fee') )      
    $cart->add_fee( __( 'Discount', 'woocommerce'), ( $discount ) );
}

要根据购物车中的商品数量确定折扣,您可以使用 WC()->cart->get_cart_contents_count();

然后可以在 woocommerce_cart_calculate_fees 动作挂钩中应用。

所以你得到:

// Add a custom checkbox fields after billing fields
function action_woocommerce_after_checkout_billing_form( $checkout ) {
    // Add a custom checkbox field
    woocommerce_form_field( 'discount30', array(
        'type'  => 'checkbox',
        'label' => __( ' Senior', 'woocommerce' ),
        'class' => array( 'form-row-wide' ),
    ), '' );   
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );

// Remove "(optional)" label on "discount30" field
function filter_woocommerce_form_field( $field, $key, $args, $value ) {
    // Only on checkout page
    if ( $key === 'discount30'  && is_checkout() ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    
    return $field;
}
add_filter( 'woocommerce_form_field' , 'filter_woocommerce_form_field', 10, 4 );

// jQuery - Ajax script
function action_wp_footer() {
    // Only on Checkout
    if ( is_checkout() && ! is_wc_endpoint_url() ) :

    if ( WC()->session->__isset('enable_fee') )
        WC()->session->__unset('enable_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if ( typeof wc_checkout_params === 'undefined' ) 
            return false;

        $( 'form.checkout' ).on( 'change', 'input[name=discount30]', function(e) {
            var fee = $(this).prop('checked') === true ? '1' : '';

            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'enable_fee',
                    'enable_fee': fee,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                },
            });
        });
    });
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'action_wp_footer' );

// Get Ajax request and saving to WC session
function get_enable_fee() {
    if ( isset($_POST['enable_fee']) ) {
        WC()->session->set( 'enable_fee', ( $_POST['enable_fee'] ? true : false ) );
    }
    die();
}
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );

// Add a custom 3 Cents Discount
function action_woocommerce_cart_calculate_fees( $cart ) {
    // Only on checkout
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
        return;
    
    // Get number of items in the cart.
    $items_in_cart = $cart->get_cart_contents_count();

    // Calculate
    $discount = 0.03 * $items_in_cart;

    // Apply discount
    if ( WC()->session->get('enable_fee') ) {      
        $cart->add_fee( __( 'Discount', 'woocommerce' ), -$discount );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );

注意: 获取购物车中的产品数量与购物车中的商品数量相反

改变

// Get number of items in the cart.
$items_in_cart = $cart->get_cart_contents_count();

// Calculate
$discount = 0.03 * $items_in_cart;

// Products in cart
$products_in_cart = count( $cart->get_cart() );

// Calculate
$discount = 0.03 * $products_in_cart;