Is it possible to add a product to cart with a new price using JavaScript? I have been working on a little script that calculates the price of the product. I would really like to write a function like this:
function addToCart(productID, productPrice) {
//add the product to cart with JavaScript
}
Any help or pointers would be deeply appreciated.
So far I have written 4 main files:
I have been able to send the variable from the JavaScript function to my product but I don't know how to add the product to cart.
My post.php looks like this:
EDIT: The following code works now and adds the product with the id 747
<?php
require('../../../../../../wp-load.php');
global $woocommerce;
$woocommerce->cart->add_to_cart(747);
sleep(3);
if (empty($_POST['ammount'])) {
$return['error'] = true;
$return['msg'] = 'You didnt select the amount.';
}
else {
$return['error'] = false;
$final_amount = $_POST['ammount'] * 10;
$return['msg'] = 'Youve chosen: ' . $final_amount . '.';
}
echo json_encode($return);
?>
I have found out that you can add a product into the cart using the following code in PHP:
global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);
Then I tried adding these 2 lines into my post.php and it didn't work and also the form stopped working. If I add this into my simple.php (which basically displays the product) it works fine.
My question is: How can I add a product into the cart using this setup?
To add a product using AJAX I had to include the wp-load.php into my post.php file. That way I could access to the woocommerce variable and later add the product. Look above for the code fix.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.