1

Based on Add a checkout checkbox field that enable a percentage fee in Woocommerce answer code, I've got a custom checkbox on which I need to offer discount to customers.

I'm trying to apply the custom discount of say $0.03 x product quantity e.g.

If quantity is 50 then the discount would be 50 x $0.03 = $1.5

Right now, it's deducting $0.03 from the Cart Total. Can anyone help me with achieving the required results?

Here is my code attempt:

// 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 ) );
}
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
pkguy
  • 13
  • 3

1 Answers1

1

To determine the discount based on the number of items in the cart, you can use WC()->cart->get_cart_contents_count();

Which then can be applied in the woocommerce_cart_calculate_fees action hook.

So you get:

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

Note: to get the number of products in cart opposite the number of items in cart

Change

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

// Calculate
$discount = 0.03 * $items_in_cart;

To

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

// Calculate
$discount = 0.03 * $products_in_cart;
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50