0

My question is basically nearly similar to this question, but my case is on cart page (not checkout page): Update fee dynamically based on radio buttons in Woocommerce checkout

Everytime user update cart, I will calculate the surcharge based on the number of cart items (the calculation is done via an external API)

After I calculate the surcharge successfully via API, I save the surcharge in woocommerce session but I don't know how to update the surcharge in the total cart table

I can add the surcharge to WooCommerce cart with woocommerce_cart_calculate_fee hook but for some reason, it always pick up the previous value of WC()->session->get( 'custom_charge_amount', 0); instead of the current value.

The flow:

  • User add items => go to cart => calculate the surcharge based on number of items => update woo surcharge
  • User update cart (add item, ..) => calculate the surcharge based on number of items => update woo surcharge

Javascript / jQuery code:

jQuery(document).ready(function( $ ) {

    const customCharge = {
        init: function() {
            $( document.body ).on( 'updated_cart_totals', this.get_custom_charge_amount)

            this.get_custom_charge_amount()
        },

        get_custom_charge_amount: function() {
            $.ajax({
                url: admin_obj.ajax_url,
                type : 'get',
                data : {
                    action : 'get_custom_charge_amount'
                },
                success: function( htmlResponse ) {
                    $('#custom-fee').replaceWith( htmlResponse )
                    $('body').trigger('wc_fragment_refresh') // Not work
                }
            })
        }
    }

   customCharge.init()
})

PHP code:

add_action( 'woocommerce_cart_collaterals','display_custom_cart' );

function display_custom_cart() {
    require_once plugin_dir_path( dirname( __FILE__ ) ) .
        'templates/custom-fee.php';
}

add_action( 'woocommerce_cart_calculate_fees', 'custom_surcharge', 20, 1 );

function custom_surcharge() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

        return;

    $custom_amount = WC()->session->get( 'custom_charge_amount', 0 ); // get from session
    $woocommerce->cart->add_fee( __('Custom charge'), $custom_amount, true, '' );
}


// WP AJAX HANDLE
add_action('wp_ajax_get_compensate_amount', 'get_custom_charge_amount');
add_action('wp_ajax_nopriv_get_custom_amount','get_custom_charge_amount');

public function get_custom_charge_amount() {
    // calculate amount here
    $custom_amount = 10 * WC()->cart->get_cart_contents_count(); // This is based on the cart item, should calculate on external API

    WC()->session->set( 'custom_charge_amount', $custom_amount ); //set session

    global $woocommerce;

    require_once plugin_dir_path( dirname( __FILE__ ) ) . 'templates/custom-fee.php';
    wp_die();
}

PHP / HTML code (in "custom-fee" template):

<?php $custom_amount = WC()->session->get( 'custom_charge_amount', 0); ?>

<div id="custom-fee" class="custom-cart">
    <p>This is custom cart</p>
    <input id="custom-checkbox" type="checkbox">
    <span class="custom-cart__amount"><?php echo $custom_amount; ?></span>
</div>

Any help will be highly appreciated.

I add the surcharge via woocommerce_cart_calculate_fees

add_action( 'woocommerce_cart_calculate_fees', 'custom_surcharge', 20, 1 );

function custom_surcharge() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

        return;

    $custom_amount = WC()->session->get( 'custom_charge_amount', 0 ); // get from session
    $woocommerce->cart->add_fee( __('Custom charge'), $custom_amount, true, '' );
}
coinhndp
  • 2,281
  • 9
  • 33
  • 64
  • 1
    I update those hooks –  coinhndp May 10 '20 at 15:03
  • Where is loaded your custom template in cart, which is the location exactly? – LoicTheAztec May 10 '20 at 15:21
  • I load it in this hook 'woocommerce_cart_collaterals'. You can use this to visualize https://businessbloomer.com/woocommerce-visual-hook-guide-cart-page/ –  coinhndp May 10 '20 at 15:24
  • I update the code. The $custom_amount = WC()->session->get( 'custom_charge_amount', 0 ) always pick up the previous value in my session so I think the code runs before the WC()->session->set( 'custom_charge_amount') which is in the PHP Ajax handle function –  coinhndp May 10 '20 at 15:26
  • Where do you calculate the fee (where do you call the external API)? is it from called from javascript or php? where do you call it exactly? why are you using a checkbox in your html as the fee calculation is made on cart items and changes on them (or not)? may be you don't need ajax… – LoicTheAztec May 10 '20 at 16:15
  • 1
    I call the external API here: $custom_amount = 10 * WC()->cart->get_cart_contents_count(); (In the Ajax handle but right now I just hardcode it 10*amount for simplicity). I have the checkbox because later I will have the feature that if user ticks on the checkbox, I will add surcharge to the cart, if not I won't add the surcharge (the surchage value will be calculated via external api but let's hardcode it for now). I tried to solve the dynamic surcharge first and when it works then I will continue with the checkbox later –  coinhndp May 10 '20 at 17:19
  • I am just the beginner when it comes to Wordpress. I wonder when we need the Ajax and when not. My flow is that the jquery will listen to some event (button click, etc) => send to Wordpress => update wordpress database or sth => send response back to jquery => update UI. I don't know if it is the right way. –  coinhndp May 10 '20 at 17:22
  • Could you help? I tried it a few days but no hope @LoicTheAztec –  coinhndp May 11 '20 at 13:45

0 Answers0