简体   繁体   中英

Woocommerce, add product(s) to cart, request failing

So I am currently learning the WordPress/WooCommerce framework. 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.

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 .

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:

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:

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:

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.
        });
    });
});

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.

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