Hello Florian,
I assume that you have this code in your child theme’s functions.php. You can add the following:
// Enqueue js file residing in current (parent or child) theme and enable Ajax url in this file through wp_localize_script.
add_action( 'wp_enqueue_scripts', 'taisho_weight_update' );
function taisho_weight_update() {
wp_enqueue_script( 'taisho-weight-update', get_stylesheet_directory_uri() . '/js/weight_update.js', array('jquery'));
wp_localize_script( 'taisho-weight-update', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
// Update custom weight on the cart page with Ajax.
add_action('wp_ajax_ajax_update_weight', 'ajax_update_weight');
add_action('wp_ajax_nopriv_ajax_update_weight', 'ajax_update_weight');
function ajax_update_weight() {
global $woocommerce;
echo '<small>Gewicht Ihrer Bestellung: ' . $woocommerce->cart->cart_contents_weight . ' ' . get_option('woocommerce_weight_unit') . '</small>';
die();
}
This code works when you have a folder named “js” within your child theme folder and inside “js” folder, a file “weight_update.js” with this code:
jQuery(document.body).on('updated_cart_totals', function () {
jQuery.ajax(
{
type: "post",
url: my_ajax_object.ajax_url,
data: {
action: 'ajax_update_weight'
},
success: function(response){
jQuery('p.total-weight').html(response);
}
});
});
Weight will update with a small delay compared to other cart totals, but with a fast website, it’s hardly noticeable.
-
This reply was modified 5 years, 5 months ago by taisho.