So I'm developing a plugin for woocommerce, and I have added a selection for packing, either in a plastic bag or in Cartoon Box with each having a different cost.
Ones the user selects one of the options I need the WordPress to refresh the prices and update the cost by adding in the correct fee by using:
WC_Cart $cart->add_fee( 'Emballagegebyr', intval($fees));
What is the best way to have the WC_Cart fee added and update the price? and how should the code look like?
And is it okay to use $_GET and $_POST to get the values or even better is there a way to use AJAX to update the price without refreshing the page?
Currently, I'm using $_GET to get the data from the browser by the following code
function at87_add_custom_fees( WC_Cart $cart ){
$fees = 3; // fee amount
$fees = isset($_GET['test']) ? $_GET['test'] : 3;
$cart->add_fee( 'Emballagegebyr', intval($fees));
}
and my plan is then to maybe add a Javascript code like below to then use the radio button to refresh the page and pass the selected option.
add_action( 'wp_footer', 'woocommerce_add_gift_box' );
function woocommerce_add_gift_box() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
// $('#add_gift_box').click(function(){
// jQuery('body').trigger('update_checkout');
// });
$("#pakpose1 input:radio").change(function(){
// Do something interesting here
alert("test");
});
});
</script>
<?php
}
}
I'm not sure though if this is the smartest way to do it, and or if there is another way, that could be better, and what security affect it might have, maybe there are some hooks that can get the same job done.
BTW: To get the radio buttons in the checkout-page I have made the plugin in such way that it override the woocommerce review-order.php
and added the radio buttons in that template as following:
<tr class="packing-selections">
<th>Pakning</th>
<td>
<input type="radio" id="pakpose1" name="pakpose" value="pakpose" checked="checked">Pak i pose <?php echo get_woocommerce_currency_symbol() ?>3.00<br>
<input type="radio" id="pakpose2" name="pakpose" value="pakkasse">Pak i papkasse <?php echo get_woocommerce_currency_symbol() ?>9.00
</td>
</tr>
This needs Ajax and can not be done without it… Here is the Ajax way. In this code you got everything, so remove your related customizations before trying it (meaning remove your radio buttons from template and all related code)…
The complete code (nothing else needed):
Code goes in function.php file of your active child theme (or active theme). Tested and works.