Woocommerce aJax apply coupon code in checkout page - php

I am moving the WooCommerce Coupon input field bellow order total by editing the review-order.php Checkout Page using this method
but the problem is applying coupon with ajax is not working.
SO my goal is to implement the ajax feature on apply coupon.
So what I am trying
My PHP ajax action function
function implement_ajax_apply_coupon() {
global $woocommerce;
// Get the value of the coupon code
//$code = $_REQUEST['coupon_code'];
$code = filter_input( INPUT_POST, 'coupon_code', FILTER_DEFAULT );
// Check coupon code to make sure is not empty
if( empty( $code ) || !isset( $code ) ) {
// Build our response
$response = array(
'result' => 'error',
'message' => 'Code text field can not be empty.'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
}
// Create an instance of WC_Coupon with our code
$coupon = new WC_Coupon( $code );
// Check coupon to make determine if its valid or not
if( ! $coupon->id && ! isset( $coupon->id ) ) {
// Build our response
$response = array(
'result' => 'error',
'message' => 'Invalid code entered. Please try again.'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
} else {
if ( ! empty( $code ) && ! WC()->cart->has_discount( $code ) ){
WC()->cart->add_discount( $code ); // apply the coupon discount
// Build our response
$response = array(
'result' => 'success',
'message' => 'successfully added coupon code'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
}
}
}
add_action('wp_ajax_ajaxapplucoupon', 'implement_ajax_apply_coupon');
add_action('wp_ajax_nopriv_ajaxapplucoupon', 'implement_ajax_apply_coupon');
and My script is
( function($) {
$( document ).ready( function() {
$( '#apply_coupon').click( function( ev ) {
// Prevent the form from submitting
ev.preventDefault();
// Get the coupon code
var code = $( '#coupon_code').val();
var button = $( this );
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
$.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
$( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
$(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
});
})(jQuery);
My AJax Action function return nothing Please help.

data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
Should be:
var data = {
action: 'ajaxapplucoupon',
coupon_code: code
};

I know i am late, we got why submit not working .
As you shared article link - if we fallow the same then coupon code not working because you are using checkout coupon form inside checkout form means form within form so first remove form tag form coupon html and use like this:
<tr class="coupon_checkout">
<td colspan="2">
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
?>
<i class="fa fa-plus"></i> REDEEM A PROMO CODE/GIFT VOUCHER
<div class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" id="checkout_coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input id="checkout_apply_coupon" type="button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
</div>
</td>
</tr>
Then add jquery either your custom.js file or directly on footer page like this:
<script>
jQuery(document).on('click','#checkout_apply_coupon', function() {
// Get the coupon code
var code = jQuery( '#checkout_coupon_code').val();
var button = jQuery( this );
alert(code);
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
jQuery.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
jQuery( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
jQuery(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
</script>
Its working in my checkout page:
https://www.loom.com/share/7dfc833895d248f191ba327cf5290403

Related

Custom checkbox that adds a fee in WooCommerce cart page

Based on Display a checkbox that add a fee in Woocommerce checkout page answer code I am trying to change usage to Cart page, rather than checkout page per clients request.
So far I managed to display custom fee check box on cart page and trigger Ajax.
However Cart totals are not updated.
If someone can help on code or point me in right direction?
// Display the custom checkbox field in cart
add_action( 'woocommerce_cart_totals_before_order_total', 'fee_installment_checkbox_field', 20 );
function fee_installment_checkbox_field(){
echo '<tr class="packing-select"><th>Priority Dispatch</th><td>';
woocommerce_form_field( 'priority_fee', array(
'type' => 'checkbox',
'class' => array('installment-fee form-row-wide'),
'label' => __(' $20.00'),
'placeholder' => __(''),
), WC()->session->get('priority_fee') ? '1' : '' );
echo '<div class="tooltip">?
<span class="tooltiptext">By selecting this option... </span>
</div></td>';
}
// jQuery - Ajax script
add_action( 'wp_footer', 'woo_add_cart_fee' );
function woo_add_cart_fee() {
// Only on Checkout
if( ! is_wc_endpoint_url() ) :
if( WC()->session->__isset('priority_fee') )
WC()->session->__unset('priority_fee')
?>
<script type="text/javascript">
jQuery( function($){
//if (typeof wc_add_to_cart_params === 'undefined')
// return false;
$('tr.packing-select').on('change', 'input[name=priority_fee]', function(){
console.log('tests');
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
//url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'priority_fee',
'priority_fee': fee,
},
success: function (response) {
$('body').trigger('added_to_cart');
},
});
});
});
</script>
<?php
endif;
}
// Get Ajax request and saving to WC session
add_action( 'wp_ajax_priority_fee', 'get_priority_fee' );
add_action( 'wp_ajax_nopriv_priority_fee', 'get_priority_fee' );
function get_priority_fee() {
if ( isset($_POST['priority_fee']) ) {
WC()->session->set('priority_fee', ($_POST['priority_fee'] ? true : false) );
}
die();
}
// Add a custom calculated fee conditionally
add_action( 'woocommerce_cart_calculate_fees', 'set_priority_fee' );
function set_priority_fee( $cart ){
if ( is_admin() && ! defined('DOING_AJAX') )
return;
if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
return;
if ( 1 == WC()->session->get('priority_fee') ) {
$items_count = WC()->cart->get_cart_contents_count();
$fee_label = sprintf( __( "PRIORITY DISPATCH %s %s" ), '×', $items_count );
$fee_amount = 20;
WC()->cart->add_fee( $fee_label, $fee_amount );
}
}
add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_installment_checkbox', 10, 4 );
function remove_optional_txt_from_installment_checkbox( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'priority_fee' === $key ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
Additionally is this the way this should be done, or is there an easier way to do it?
There are some mistakes in your code. Also, on cart page, jQuery events and Ajax behavior are a bit different, so it requires some changes:
// Display the checkout field in cart page totals section
add_action( 'woocommerce_cart_totals_before_order_total', 'display_priority_fee_checkbox_field', 20 );
function display_priority_fee_checkbox_field(){
echo '<tr class="installment-section">
<th>'.__("Priority Dispatch").'</th><td>';
woocommerce_form_field( 'priority_fee', array(
'type' => 'checkbox',
'class' => array('form-row-wide'),
'label' => __(' $20.00'),
), WC()->session->get('priority_fee') ? '1' : '' );
echo '<div class="tooltip">?
<span class="tooltiptext">'.__("By selecting this option... ").'</span>
</div></td>';
}
// Remove "(optional)" text from the field
add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_priority_fee_checkbox', 10, 4 );
function remove_optional_txt_from_priority_fee_checkbox( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'priority_fee' === $key ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// jQuery :: Ajax script
add_action( 'wp_footer', 'priority_fee_js_script' );
function priority_fee_js_script() {
// On Order received page, remove the wc session variable if it exist
if ( is_wc_endpoint_url('order-received')
&& WC()->session->__isset('priority_fee') ) :
WC()->session->__unset('priority_fee');
// On Cart page: jQuert script
elseif ( is_cart() ) :
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
var c = 'input[name=priority_fee]';
$(document.body).on( 'click change', c, function(){
console.log('click');
var fee = $(c).is(':checked') ? '1' : '';
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'priority_fee',
'priority_fee': fee,
},
success: function (response) {
setTimeout(function(){
$(document.body).trigger('added_to_cart');
}, 500);
},
});
});
});
</script>
<?php
endif;
}
// Get Ajax request and saving to WC session
add_action( 'wp_ajax_priority_fee', 'priority_fee_ajax_receiver' );
add_action( 'wp_ajax_nopriv_priority_fee', 'priority_fee_ajax_receiver' );
function priority_fee_ajax_receiver() {
if ( isset($_POST['priority_fee']) ) {
$priority_fee = $_POST['priority_fee'] ? true : false;
// Set to a WC Session variable
WC()->session->set('priority_fee', $priority_fee );
echo $priority_fee ? '1' : '0';
die();
}
}
// Add a custom calculated fee conditionally
add_action( 'woocommerce_cart_calculate_fees', 'set_priority_fee' );
function set_priority_fee( $cart ){
if ( is_admin() && ! defined('DOING_AJAX') )
return;
if ( WC()->session->get('priority_fee') ) {
$item_count = $cart->get_cart_contents_count();
$fee_label = sprintf( __( "PRIORITY DISPATCH %s" ), '× ' . $item_count );
$fee_amount = 20 * $item_count;
$cart->add_fee( $fee_label, $fee_amount );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

woocommerce_cart_calculate_fees: Update Fee on custom input change

Image Issue Example
At the WooCommerce "checkout" page:
I would like to input any number in the "Custom Fee Input"
- then it will be calculated in the "Total price table".
- After placing order the "Custom Fee" will be auto synchronized into the database.
Recommendation: using Plain JavaScript instead of jQuery is highly appreciated.
This is my codes:
html
<label>
Custom Fee
<input id="custom_fee" name="custom_fee" type="number" required>
</label>
Plain JavaScript
var $custom_fee = document.getElementById("custom_fee");
$custom_fee.addEventListener("change", function(){
var data = {
action: 'custom_fee',
security: wc_checkout_params.apply_state_nonce,
custom_fee_cost: $custom_fee.value,
};
var request = new XMLHttpRequest();
request.open('POST', wc_checkout_params.ajax_url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = this.response;
console.log(resp);
} else {
var resp = this.response;
console.log(resp);
}
};
request.send(data);
});
function.php
add_action('wp_ajax_custom_fee', 'custom_fee_ajax', 10);
add_action('wp_ajax_nopriv_custom_fee', 'custom_fee_ajax', 10);
function custom_fee_ajax() {
if( ! is_checkout() ) return;
global $wpdb;
if( isset($_POST['custom_fee']) ){
$custom_fee = $_POST['custom_fee'];
WC()->session->set( 'custom_fee', $custom_fee );
echo json_encode( WC()->session->get('custom_fee' ) );
}
die();
}
//________________________________________________________
add_action('woocommerce_cart_calculate_fees', 'custom_fee');
function custom_fee() {
if( ! is_checkout() ) return;
session_start();
global $woocommerce;
if ( !defined( 'DOING_AJAX' ) ) return;
$fee = $_SESSION['custom_fee'];
$woocommerce->cart->add_fee( 'Custom Fee' , $fee, true, '' );
}
NOTE: The above code does not work correctly (bad request 400; php functions); so I would like to have someone help I to solve this issue.

Update Total in checkout of Woocommerce with Ajax Request

Before asking question on SO, I searched a lot about what I needed to make a ajax request with WordPress. All my code and the request is working, but is not doing what I need it to do.
What I need to do is When I click at the buttom on checkout page "Novo Dependente", the information with the values to calculate total must update. "Total" value must be updated with a value which I defined at product post type page on admin panel. This value I already get, but the updating the value is real problem to me.
This is the page that I working.
This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax.
And here my code goes
Obs: it's a plugin.
Here is the php code.
public function add_total_value()
{
if (! $_POST['action'] || $_POST['action'] !== 'add_total_value' ) :
echo json_encode(
array(
'status' => 'failed',
'message' => 'erro'
)
);
wp_die();
endif;
$woocommerce;
$quantidadeDependentes = $_POST['quantiaDependentes'];
//$produto_valor = WC()->cart->total;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
{
$product = $cart_item['data'];
$item_id = $cart_item['product_id'];
$endereco_igual = get_post_meta( $item_id, 'adicional_mesmo', true);
$endereco_igual = str_replace(',', '.', $endereco_igual);
$endereco_igual = floatval( filter_var( $endereco_igual, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) );
$produtoValor = floatval( get_post_meta( $item_id, '_regular_price', true) );
$valorTotal = $produtoValor + ( $endereco_igual * $quantidadeDependentes );
WC()->cart->total = $valorTotal;
WC()->cart->calculate_totals();
wc_price($valorTotal);
}
echo json_encode(
array(
'status' => 'success',
'valorTotal' => wc_price($valorTotal)
));
wp_die();
}
My Ajax request
function contagemDependentes()
{
$contagem = jQuery('.woocommerce-dependentes-contagem');
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length;
if ( quantiaDependentes <= 0 ) {
var mensagemNumeroDependentes = 'Nenhum dependente informado';
} else if ( quantiaDependentes === 1 ) {
var mensagemNumeroDependentes = '1 dependente';
} else {
var mensagemNumeroDependentes = quantiaDependentes+' dependentes';
}
jQuery($contagem).html(mensagemNumeroDependentes);
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length + 1;
var dados = {
action: 'add_total_value',
quantiaDependentes: quantiaDependentes
};
jQuery.ajax({
type: 'POST',
url: custom_values.ajaxurl,
data: dados,
dataType: 'json',
success: function(response)
{
console.log(response);
if (response.status === 'success')
{
console.log(response.status);
console.log(response.valorTotal);
var html = "<tr class='order-total'>";
html += "<th>Total</th>";
html += "<td>";
html += response.valorTotal;
html += "</td>";
html += "</tr>";
jQuery( '.order-total' ).remove();
jQuery( 'tfoot' ).append( html );
jQuery( 'body' ).trigger( 'update_checkout' );
}
}
});
}
before function() in functions.php always must be such code
add_action('wp_ajax_your_function_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_function_name', 'your_function_name');

Woocommerce: Pay half (50%) on Cash on delivery using ajax

I am trying to make a ajax function to make users pay half the price of total amount, on custom cash on delivery method. When user selects yes or no radio button total amount is changed accordingly.
This: Link is a great example what I am trying to follow but I need to make it as a ajax call.
Here's how I added new fields before payment block:
add_action("woocommerce_review_order_before_payment", "new_buttons");
function new_buttons(){
echo '<div id="cash-on-delivery-wrap" class="cash-on-delivery-wrap">';
echo '<h5>Cash on delivery: </h5><div style="clear:both"></div>';
echo '<h6>Pay half 50%</h6><div style="clear:both"></div>';
echo '<div class="cod_button_wrap">';
echo '<label><input type=radio value="no" name="new-cod" checked/>No</label>';
echo '<label><input type=radio value="yes" name="new-cod" />Yes</label>';
echo '</div>';
echo '</div>';
}
Here is the JS:
jQuery(document).ready(function(){
jQuery("form.checkout").on("change", "#cash-on-delivery-wrap input",
function(){
var data = {
action: 'change_cod',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery( 'form.checkout' ).serialize()
};
jQuery.post( ajaxurl, data, function( response )
{
jQuery( 'body' ).trigger( 'update_checkout' );
});
});
});
Here is the function:
function custom_cart_total() {
$current_state = $_POST['post_data'];
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if($current_state=='yes'){
WC()->cart->total *= 0.50;
}else{
WC()->cart->total;
}
exit;
}
add_action( 'wp_ajax_nopriv_change_cod', 'custom_cart_total' );
add_action( 'wp_ajax_change_cod', 'custom_cart_total' );
Cant seem to make it work, what am I missing here.
Note: The code in the linked answer, is only changing the displayed total amount in cart and checkout, but doesn't change it for real.
This answer is also changing the displayed checkout total amount. We need another function hooked in the order creation process, to update the total amount.
For Wordpress Ajax you need to register your script in an external JS file that you will upload in your active theme folder inside a js subfolder. Let say that this external file name will be pay_half.js.
1) Here is the function that will do that registration and will enable WordPress Ajax functionality:
add_action( 'wp_enqueue_scripts', 'ajax_change_shipping' );
function ajax_change_shipping() {
// Only on front-end and checkout page
if( is_admin() || ! is_checkout() ) return;
// Get the Path to the active theme or child theme or plugin folder
# $path = plugin_dir_url( __FILE__ ); // A plugin
# $path = get_template_directory_uri(); // A Normal theme
$path = get_stylesheet_directory_uri(); // A child theme
// Define the subfolder name
$subfolder = 'js';
// Define the file name
$filename = 'pay_half.js';
// Reference name of the script (should be unique)
$handle = 'pay-half';
// Set the ajaxurl parameter used in your script
$data = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
// The variable name whichwill contain the data
$name = 'pay_half';
// Registering the javascript file and enqueues it.
wp_enqueue_script( $handle, $path."/$subfolder/$filename", array( 'jquery' ), '1.0', true );
// Localizing the registered script (Here using Ajax)
wp_localize_script( $handle, $name, $data );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
2) Now the Javascript/jQuery external file (named: pay_half.js):
jQuery(document).ready(function ($) {
var selectHalf = '#cash-on-delivery-wrap input[type="radio"]',
paymentMethod = 'input[name^="payment_method"]',
codWrap = $('.cash-on-delivery-wrap'),
cartGTotal = $('input#cart_gtotal').val(),
codPartial;
// Detecting payment method on load to show/hide cod custom options
if( $(paymentMethod+':checked').val() == 'cod' )
codWrap.show("fast");
else
codWrap.hide("fast");
// Live detecting choosen payment method to show/hide cod custom options
$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
if ( $(paymentMethod+':checked').val() == 'cod' ) {
codWrap.show("fast");
} else {
codWrap.hide("fast");
$('#cash-on-delivery-wrap input#cod-options_no').prop('checked', true);
}
$(document.body).trigger("update_checkout");
// console.log($(paymentMethod+':checked').val());
});
// The "Cod" custom options (ajax)
$(selectHalf).click(function(){
if($(selectHalf+':checked' ).val() == 'yes' ) codPartial = 'yes';
else codPartial = 'no';
$.ajax({ // This does the ajax request
url: pay_half.ajaxurl,
type : 'post',
data: {
'action':'cod_partial_payment', // Name of the php function
'cod_partial' : codPartial // Passing this variable to the PHP function
},
success:function(data) {
// Displaying the price (Ajax)
$( 'table.shop_table > tfoot > tr.order-total > td > strong > span' ).html(data.price_html);
if(codPartial == 'yes')
$('input#cart_remaining').val(data.price_remaining);
else
$('input#cart_remaining').val(0);
$(document.body).trigger("wc_fragment_refresh");
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
3) The Display of your custom fields (revisisted).
I have added 2 hidden fields with the total amount and the remaining amount to pay.
add_action( 'woocommerce_review_order_before_payment', 'cod_payment_options', 10 );
function cod_payment_options(){
echo '<style>.cod-button-options label{display:inline-block; margin:0 6px;}</style>
<div id="cash-on-delivery-wrap" class="cash-on-delivery-wrap">
<h3>' . __( 'Cash on delivery option' ) . '</h3>';
woocommerce_form_field( 'cod-options', array(
'type' => 'radio',
'class' => array('form-row-wide', 'cod-button-options'),
'label' => __( '<b>Pay half (50%): </b>' ),
'required' => false,
'options' => array(
'no' => __( 'No' ),
'yes' => __( 'Yes' ),
)
), 'no' );
// Some additional hidden fields
echo '<input type="hidden" id="cart_gtotal" name="cart_gtotal" value="'. WC()->cart->total .'">
<input type="hidden" id="cart_remaining" name="cart_remaining" value="0" />
</div>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
4) The driven php function (Wordpress Ajax):
add_action( 'wp_ajax_nopriv_cod_partial_payment', 'cod_partial_payment' );
add_action( 'wp_ajax_cod_partial_payment', 'cod_partial_payment' );
function cod_partial_payment() {
if( ! isset($_POST['cod_partial']) ) return;
$current_state = $_POST['cod_partial'];
$remaining = 0;
if( $current_state == 'yes' ){
WC()->cart->total /= 2;
}
WC()->session->set( 'total', WC()->cart->total );
$response = array(
'price_html' => wc_price( WC()->cart->total ),
'price_remaining' => WC()->cart->total,
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
die(); // Always (to avoid an error 500)
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
5) All Other php functions (Update order amount, save metadata, display a message):
// Replacing the total amount when COD option is enabled
add_action( 'woocommerce_checkout_create_order', 'cod_options_change_order_total_ammount', 10, 2 );
function cod_options_change_order_total_ammount( $order, $data ) {
if ( ! empty( $_POST['cod-options'] ) && $_POST['cod-options'] == 'yes' ) {
$remaining = sanitize_text_field( $_POST['cart_remaining'] );
$total = WC()->cart->total - floatval($remaining);
WC()->session->set( 'total', $total );
$order->set_total( $total );
}
}
// Updating order meta data for Cod selected option
add_action( 'woocommerce_checkout_update_order_meta', 'cod_options_update_order_meta', 10, 1 );
function cod_options_update_order_meta( $order_id ) {
if ( ! empty( $_POST['cod-options'] ) && $_POST['cod-options'] == 'yes' ) {
update_post_meta( $order_id, '_cod_remaining_amount', sanitize_text_field( $_POST['cart_remaining'] ) );
update_post_meta( $order_id, '_cod_partial_paid_amount', sanitize_text_field( $_POST['cart_gtotal'] - $_POST['cart_remaining'] ) );
}
update_post_meta( $order_id, '_cod_partial_payment_option', sanitize_text_field( $_POST['cod-options'] ) );
}
// Displaying the remaining amount to pay in a custom message on Order received page (thank you)
add_action( 'woocommerce_thankyou_cod', 'cod_options_woocommerce_thankyou', 10, 1 );
function cod_options_woocommerce_thankyou( $order_id ) {
if( get_post_meta( $order_id, '_cod_partial_payment_option', true ) == 'yes' ){
$ra = '<span style="color:#96588a;">'.wc_price( get_post_meta( $order_id, '_cod_remaining_amount', true )).'</span>';
?>
<ul class="woocommerce-order-overview woocommerce-thankyou-cod-options order_details">
<li class="woocommerce-order-overview__remaining_total order">
<strong><?php echo __("There is a remaining amount of $ra to pay on this order."); ?></strong>
</li>
</ul>
<?php
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested on Woocommerce 3+ and works.

Woocommerce added custom fee, trying to manipulate with checkbox via AJAX

i was hoping if i could get some information about whats going on in here.
I added an extra fee in the totals part of the checkout, it adds the 10% of the subtotal.
Now this works since i added the following code snippet via a plugin:
add_action( 'woocommerce_cart_calculate_fees','endo_handling_fee' );
function endo_handling_fee() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$subtotal = $woocommerce->cart->subtotal;
$fee_percentage = 0.1; // 10 percent
$fee = ($subtotal * $fee_percentage);
$woocommerce->cart->add_fee( 'Seguro de Envio', $fee, true, 'standard' );
}
And it actually works but i have to be able to activate it via a checkbox.
Check box was created by going into cart-totals and using this code:
<?php foreach ( WC()->cart->get_fees() as $fee ) : ?>
<tr class="fee">
<th><?php echo esc_html( $fee->name ); ?> <input type="checkbox" id="envio"> </th>
<td id="seguroenvio" data-title="<?php echo esc_html( $fee->name ); ?>"><? php wc_cart_totals_fee_html( $fee ); ?></td>
</tr>
<?php endforeach; ?>
Also at the bottom of cart-totals.php file, i added this:
<?php do_action( 'woocommerce_after_cart_totals' ); ?>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/javascript">
$("#envio").on("change", function() {
var mee = ($(this).is(":checked") == true) ? "yes" : "no";
$.ajax({
type: 'post',
url: 'http://valaidp.com/mrelectronicstest/wp- content/plugins/woocommerce/templates/cart/fields.php',
data: {status:mee},
success: function(output) {
$('#seguroenvio').text(output);
}
});
});
</script>
<?php
function custom_checkbox_checker () {
if ( is_checkout() ) {
wp_enqueue_script( 'jquery' ); ?>
<script type="text/javascript">
jQuery(document).ready( function (e) {
var $ = jQuery;
// wc_checkout_params is required to continue, ensure the object exists
if ( typeof wc_checkout_params === 'undefined' )
return false;
var updateTimer,
dirtyInput = false,
xhr;
function update_shipping() {
if ( xhr ) xhr.abort();
var liftgate = $( '#envio:checked' ).val();
var data = {
action: 'woocommerce_update_order_review',
security: wc_checkout_params.update_order_review_nonce,
liftgate: liftgate,
post_data: $( 'form' ).serialize()
};
xhr = $.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: data,
success: function( response ) {
if ( response ) {
//$( '#order_review' ).html( $.trim( response ) );
$( '#order_review' ).find( '#envio:checked' ).trigger('click');
$( 'body' ).trigger('updated_checkout' );
}
}
});
}
jQuery('#envio').on('click', function() {
update_shipping();
$woocommerce->cart->add_fee( 'Seguro de Envio', $fee, true, 'standard' );
});
});
</script>
<?php }
}
And to finish off, in the same location of the cart-totals.php i added a fields.php file that i created adding this code:
<?php
global $woocommerce;
add_action( 'woocommerce_cart_calculate_fees','endo_handling_fee' );
/*global $woocommerce;
$subtotal = $woocommerce->cart->subtotal;
$fee_percentage = 0.1; // 10 percent
$fee = ($subtotal * $fee_percentage);
$woocommerce->cart->add_fee( 'Seguro de Envio', $fee, true, 'standard' );
echo $fee." ";
require('../../../../../wp-includes/functions.php'); */
function endo_handling_fee() {
global $woocommerce;
if (is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$subtotal = $woocommerce->cart->subtotal;
$fee_percentage = 0.1; // 10 percent
$fee = ($subtotal * $fee_percentage);
if($_POST["status"] == "yes"){
$woocommerce->cart->add_fee( 'Seguro de Envio', $fee, true, 'standard' );
echo $fee." ";
}
else
{
$woocommerce->cart->add_fee( 'Seguro de Envio', 0, true, 'standard' );
echo "0";
}
echo 0;
}
?>
The checkbox appears but its not triggering anything when clicked.
Any help is much appreciated.
Woocommerce version 4.4.2
Site url: valaidp.com/mrelectronicstest

Categories