简体   繁体   English

如何使用JavaScript在WooCommerce中将产品添加到购物车

[英]How to add product to cart in WooCommerce using JavaScript

Is it possible to add a product to cart with a new price using JavaScript? 是否可以使用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: 到目前为止,我已经编写了4个主要文件:

  • functions.js - calculates and shows the current price based on options the customer chooses (this works fine) functions.js-根据客户选择的选项计算并显示当前价格(这很好)
  • ajaxSubmit.js - jQuery ajax to send the variables to my PHP files (sends successfully) ajaxSubmit.js-jQuery ajax将变量发送到我的PHP文件(成功发送)
  • post.php - file where the variables are sent post.php-将变量发送到的文件
  • simple.php - the single product PHP file which displays the product simple.php-显示产品的单个产品PHP文件

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. 我已经能够将变量从JavaScript函数发送到我的产品,但是我不知道如何将产品添加到购物车。

My post.php looks like this: 我的post.php看起来像这样:

EDIT: The following code works now and adds the product with the id 747 编辑:下面的代码现在可以正常工作,并添加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: 我发现您可以使用以下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. 然后,我尝试将这两行添加到我的post.php中,但它不起作用,并且表单也停止了工作。 If I add this into my simple.php (which basically displays the product) it works fine. 如果将其添加到我的simple.php(基本上显示产品)中,则可以正常工作。

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. 要使用AJAX添加产品,我必须将wp-load.php包含到我的post.php文件中。 That way I could access to the woocommerce variable and later add the product. 这样,我可以访问woocommerce变量,然后添加产品。 Look above for the code fix. 在上面查找代码修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM