You are currently viewing Woocommerce update cart meta value using ajax wordpress action

Woocommerce update cart meta value using ajax wordpress action

Woocommerce update cart custom meta value using ajax with wordpress action defined in function.php. WordPress provides action that can be called using ajax.

Define action in wordpress function.php file

Below “product_color_callback” is a function defined in function.php that will called using ajax function.

//Define wordpress action
add_action( 'wp_ajax_product_color', 'product_color_callback' );
add_action( 'wp_ajax_nopriv_product_color', 'product_color_callback' );
function product_color_callback(){
      //update cart item product_color
	WC()->cart->cart_contents[$_POST['cart_item_key']]['product_color'] = $_POST['product_color'];
	WC()->cart->set_session();
	wp_die();
}

Above code use wp_die() to prevent result from “0”;

Ajax Code

WordPress action is added, now its time to call the defined action using ajax from your required page.

jQuery.ajax({
        type: "POST",
        url: "<?php echo admin_url('admin-ajax.php');?>",
	data:{
		action: "product_color",
		cart_item_key : cart_key,
		product_color : "Red",
	      },
	}).success(function(result){
		alert(result);	
	});

Leave a Reply