2

The amended code below is based on Add a checkout checkbox field that enable a percentage fee in Woocommerce. I have adapted but wishing to only target a specific category so when a student ticks the box at checkout, defining they are a student, it will deduct 15 percent off their total but only for a specific category range - namely 'online seminars'. It is beyond me so would appreciate some help.

// 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( 'student_discount_fee', array(
        'type'  => 'checkbox',
        'label' => __(' Yes, I am a student lawyer studying law'),
        'class' => array( 'form-row-wide' ),
    ), '' );
}

// Remove "(optional)" label on "Student discount 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( 'student_discount_fee' === $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=student_discount_fee]', 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 dynamic 15% fee
add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee( $cart ) {
    // Only on checkout
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
        return;

    $percent = -33.33333333333333;

    if( WC()->session->get('enable_fee') )
        $cart->add_fee( __( 'STUDENT LAWYER DISCOUNT', 'woocommerce')." ", ($cart->get_subtotal() * $percent / 100) );
}
// hide coupon field on cart page
function hide_coupon_field_on_cart( $enabled ) {

    if ( is_cart() ) {
        $enabled = false;
    }

    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );

// hide coupon field on checkout page
function hide_coupon_field_on_checkout( $enabled ) {

    if ( is_checkout() ) {
        $enabled = false;
    }

    return $enabled;
}
add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_checkout' );
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Herbivore
  • 23
  • 4

1 Answers1

1

Update 3

Use the following revisited code with an additional custom conditional function that check if items are only from specific product categories and can also give the non discounted subtotal for the items from your specific product category(ies).

You will have to set in that function your correct product category(ies) in the array and you can use term name(s), slug(s) or Id(s).

The subtotal is now calculated only for items from your specific product category for the discount and it's a non discounted subtotal, so you don't need to hide anymore the coupon field.

The checkbox is displayed when there is at least an item from your specific product category.

// Custom conditional function that check for specific product categories (and calculate their subtotal)
function check_cart_items_for_specific_categories( $type = 'boolean') {
    $categories     = array('online-seminars'); //  <===  Here define your product category (name, slug or Id)
    $category_found = false; // Initializing
    $item_subtotal  = 0; // Initializing

    foreach( WC()->cart->get_cart() as $item ) {
        if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) {
            $category_found = true;
            $item_subtotal += $item['line_total'];
        }
    }

    if ( $type === 'subtotal' ) {
        return $item_subtotal;
    } else {
        return $category_found;
    }
}


// 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(){
    if( ! check_cart_items_for_specific_categories() ) return; // Exit

    // Add a custom checkbox field
    woocommerce_form_field( 'student_discount_fee', array(
        'type'  => 'checkbox',
        'label' => __(' Yes, I am a student lawyer studying law'),
        'class' => array( 'form-row-wide' ),
    ), '' );
}

// Remove "(optional)" label on "Student discount 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( 'student_discount_fee' === $key && is_checkout() && check_cart_items_for_specific_categories() ) {
        $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() && check_cart_items_for_specific_categories() ) :

    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=student_discount_fee]', function() {
            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 dynamic 15% fee
add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee( $cart ) {
    // Only on checkout
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
        return;

    if( WC()->session->get('enable_fee') && check_cart_items_for_specific_categories() ) {
        $percentage = -33.33333333333333; // Set the percentage discount (negative float number)
        $subtotal   = check_cart_items_for_specific_categories('subtotal'); // Related items subtotal
        $discount   = $subtotal * $percentage / 100;

        $cart->add_fee( strtoupper( __( 'Student lawyer discount', 'woocommerce') ), $discount );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399