Update WooCommerce cart price total based on custom fields – AJAX, PHP

I am putting a few custom checkout fields into the shipping section of the WooCommerce checkout. Here is the working code:

function is_it_over_onefifty($show_shipping){
    if(is_page(5) || is_page(6)){

        global $woocommerce;
        if ($woocommerce->cart->cart_contents_weight > 150){
            //diable shipping, add freight

            return false;
        }
        else{

            //do nothing

        }
        return $show_shipping;
    }
}
add_filter( 'woocommerce_cart_ready_to_calc_shipping', 'is_it_over_onefifty', 98 );

function show_if_over_onefifty(){
    if(is_page(5) || is_page(6)){

        global $woocommerce;
        if ($woocommerce->cart->cart_contents_weight > 150){
            //show message and options
            ?>
                <tr class="over-one-fifty-shipping">
                    <th>Shipping</th>

                    <td>
                        <p>The total package weight of your cart is over 150lbs. You will need to choose a freight shipping option to continue.</p><br>
                        <form>
                            <input type="radio" name="freight" value="ourFreight" checked="checked"/>Use our freight ($300)<br><br>
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="loadDock" class="checkFork" />Do you have a loading dock or forklift?<br><br>
                            <input type="radio" name="freight" value="otherFreight" />Use other method<br><br>
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<textarea name="otherFreightMethod" placeholder="Please enter your preferred method of shipping" class="checkOther" ></textarea><br> 
                        </form>
                    </td>
                </tr>
            <?php

        }

    }
}
add_action( 'woocommerce_review_order_before_order_total', 'show_if_over_onefifty', 1);

Whats happening in the first function is I remove the original shipping methods from the checkout if the total weight of the items in the cart is over 150lbs. In the second one, I add the custom freight options I need to the shipping section. I do this because after the customer surpasses the 150lb limit, they have to choose a freight shipping option.

My question now is,

How do I dynamically update the total price of the cart based on their selections of these new fields?

As of right now they’re just useless html object sitting in my checkout. I know this has to do with the AJAX call in the cart, but I don’t know how to hook into it. I also know that you can use something like this to change the price of the cart:

global $woocommerce;
        $woocommerce->cart->add_fee( __('Custom', 'woocommerce'), 300 );

Read more here: Update WooCommerce cart price total based on custom fields – AJAX, PHP

Leave a Reply

Your email address will not be published. Required fields are marked *