简体   繁体   English

Woocommerce,将产品添加到购物车,请求失败

[英]Woocommerce, add product(s) to cart, request failing

So I am currently learning the WordPress/WooCommerce framework.所以我目前正在学习 WordPress/WooCommerce 框架。 I wanted to know how I could create a button which adds a bunch of products to the cart.我想知道如何创建一个按钮,将一堆产品添加到购物车。 Multiple at a time would be great as at the moment I'm having to loop through a list of product id's, and then launch a separate AJAX request each (see code below), this method has issues anyway as it only adds one of the items to the cart even though all requests were sent.一次多个会很棒,因为目前我必须遍历产品 ID 列表,然后每个都启动一个单独的 AJAX 请求(请参阅下面的代码),无论如何,此方法有问题,因为它只添加了一个即使所有请求都已发送,商品也已发送到购物车。

Ultimately, If i can sort the requests to adding a single product to a cart then would there be a better way of achieving what I need?最终,如果我可以对将单个产品添加到购物车的请求进行排序,那么是否有更好的方法来实现我的需求?

Code:代码:

<script>


    function add_to_cart(checkout=0){

        // grabs all the products And their qty chosen in product list view
        var arr = document.getElementsByName('qty');

        for(var i=0;i<arr.length;i++){

            var myid = arr[i].id;
            var myidtrue = myid.split("_");
            myidtrue = myidtrue[1];

            // get current qty
            var myqty = arr[i].value;

            if(myqty > 0){
                var xmlhttp = new XMLHttpRequest();     
                xmlhttp.open("POST", "http://wp/?wc-ajax=add_to_cart", true);
                xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xmlhttp.send('product_id=' + myidtrue + '&quantity=' + myqty);
                console.log("sent request for " + myidtrue + " (" + myqty + ")");
            }else{
                console.log("didnt sent request for " + myidtrue + " (" + myqty + ")");             
            }

        }
    }
</script>

There's potentially an easier way to do this, but I will walk you through the full set that I would go for in this instance, as I am unsure if you've learnt all the nuances that comes with Wordpress and AJAX .可能有一种更简单的方法来做到这一点,但我将引导您完成在这种情况下我将采用的全套方法,因为我不确定您是否已经了解了Wordpress 和 AJAX附带的所有细微差别。

First, you have to make sure that you have localized your custom JavaScript file, you do this during the wp_enqueue_scripts hook like this:首先,你必须确保你已经本地化了你的自定义 JavaScript 文件,你在wp_enqueue_scripts钩子中这样做:

add_action( 'wp_enqueue_scripts', 'my_custom_script' );
function my_custom_script() {
    wp_register_script( 'custom-js', get_template_directory_uri() . '/custom.js', array(), '20190710', true ); //this is a js file called custom.js which is directly in my theme root file i.e. example.com/wp-content/themes/my-theme-slug/custom.js
    wp_localize_script( 'custom-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script( 'custom-js');
}

Secondly, you can register your function for both logged-in and non-logged-in users by using thewp_ajax and wp_ajax_nopriv actions along with your function that adds a product to the cart programmatically , like this:其次,您可以使用wp_ajaxwp_ajax_nopriv操作以及以编程方式将产品添加到购物车的功能,为登录和未登录用户注册您的功能,如下所示:

add_action("wp_ajax_my_custom_add_to_cart", "my_custom_add_to_cart");
add_action("wp_ajax_nopriv_my_custom_add_to_cart", "my_custom_add_to_cart");
function my_custom_add_to_cart() {
    $product_ids = $_REQUEST['product_ids']; //get the product ids from your ajax function
    foreach (explode(',', $product_ids) as $product_id) { //loop through each provided product id
        if(get_post_type($product_id == 'product')) { //ensure that the id provided is valid AND a product
            WC()->cart->add_to_cart( $product_id ); //add it to cart
        }
    }
    die(); //close the connection
}

Lastly, you call the AJAX function inside your custom.js file like this:最后,您在custom.js文件中调用 AJAX 函数,如下所示:

jQuery(document).ready(function($){
    $('.my-custom-add-to-cart').click(function(){
        var my_product_ids = '123,124,125';
        var request = jQuery.ajax({
            method: "POST",
            url: myAjax.ajaxurl+'?r='+Math.random(),
            data: { action: "my_custom_add_to_cart", product_ids: my_product_ids }, //function name, along with $_REQUEST variable
            dataType: "html",
        });
        request.done(function( data ) { 
            //do whatever you want here - redirecting to checkout is normally a great idea.
        });
    });
});

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

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