Woocommerce add to cart with custom pricing
Here is the code to add to cart with custom pricing with use of ajax and jquery. Below is the code divided in three parts.
- PHP code for theme functions.php file
- JS code to run ajax
- HTML code to create ajax add to cart button
Below is the code for theme functions.php file
add_action( 'wp_ajax_add_to_cart_a', 'prefix_add_to_cart_a' );
add_action( 'wp_ajax_nopriv_add_to_cart_a', 'prefix_add_to_cart_a' );
function prefix_add_to_cart_a() {
$product_id = intval( $_POST['product_id'] );
$product_price = $_POST['product_price'];
$quantity = $_POST['qty'];
global $woocommerce;
WC()->cart->add_to_cart( $product_id, $quantity, 0, array(), array( 'cf_custom_price' => $product_price ) );
$arr['status']=1;
echo json_encode($arr);
die();
}
add_action( 'woocommerce_before_calculate_totals', 'codeflask_custom_price_refresh' );
function codeflask_custom_price_refresh( $cart_object ) {
foreach ( $cart_object->get_cart() as $item ) {
if( array_key_exists( 'cf_custom_price', $item ) ) {
$item[ 'data' ]->set_price( $item[ 'cf_custom_price' ] );
}
}
}
Below is the javascript code to run ajax:
jQuery(document).on('click','.atc_w', function(event){
event.preventDefault();
var tp = jQuery(this).html();
var t = jQuery(this);
t.html('Please wait...');
var pid = jQuery(this).attr('data-id');
var pp = jQuery(this).attr('data-pri');
var q = jQuery('.qt'+pid).val();
var data = {
action: 'add_to_cart_a',
product_id: pid,
product_price: pp,
qty: q
};
jQuery.post('/wp-admin/admin-ajax.php' , data, function(response) {
t.html('Added to Cart');
setTimeout(function(){
t.html(tp);
window.location='/cart';
},1000);
});
return false;
});
Below is the html code to create button (Replace 123 with your product id and replace 100 with the product price) :
<div class="atc_w" data-id="123" data-pri="100">Add to Cart</div>