Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce Ajax add to cart programmatically

I have this button:

<a href="http://my-site/checkout/" target="_blank" class="dt-sc-button">bla bla</a>

This button is located on my homebage and is generated by a page builder. What I want to accomplish is when somebody click on the button, it will take them on the checkout, and add a product to the cart. I know that this can be accomplished via a URL, but I need to have this button do other things as well(client idea).

So right now I'm stucked here:

JQuery

jQuery(document).ready(function($){     
$(".remove-all").click(function(){
    $.ajax({
        url: "wp-admin/admin-ajax.php",
        data: 'myajax'
    });
  });
});

PHP

add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');

    function myajax() {
        global $woocommerce;
        $product_id = 264;
    $woocommerce->cart->add_to_cart($product_id);
    die();
    }

I'm a javascript noob, so can you please point me to the right direction, or maybe give me a hint on what I'm doing wrong.

Thanks in advance!

like image 956
Marian Ioan Avatar asked Nov 11 '15 17:11

Marian Ioan


1 Answers

As I mentioned in the comments, you can pretty much borrow from core WooCommerce functions.

First, here's the button we'll be trying to ajaxify:

<a href="http://local.wordpress.dev/checkout/" class="button test-button">bla bla</a>

Secondly, we'll load our custom script and pass it important variables such as the admin ajax and checkout urls.

add_action( 'wp_enqueue_scripts', 'so_load_script', 20 );
function so_load_script(){
    wp_enqueue_script( 'so_test', plugins_url( 'js/test.js', __FILE__ ) );
    $i18n = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'checkout_url' => get_permalink( wc_get_page_id( 'checkout' ) ) );
    wp_localize_script( 'so_test', 'SO_TEST_AJAX', $i18n );
}

Now we will write our ajax callbacks, which is copied almost verbatim from WooCommerce core with only a few small modifications:

add_action('wp_ajax_myajax', 'myajax_callback');
add_action('wp_ajax_nopriv_myajax', 'myajax_callback');

    /**
     * AJAX add to cart.
     */
function myajax_callback() {        
        ob_start();

        //$product_id        = 264;
        $product_id        = 34;
        $quantity          = 1;
        $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
        $product_status    = get_post_status( $product_id );

        if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {

            do_action( 'woocommerce_ajax_added_to_cart', $product_id );

            wc_add_to_cart_message( $product_id );

        } else {

            // If there was an error adding to the cart, redirect to the product page to show any errors
            $data = array(
                'error'       => true,
                'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
            );

            wp_send_json( $data );

        }

        die();

}

And finally the contents of test.js:

jQuery(document).ready(function($){     
  $(".test-button").click(function(e){ 
    e.preventDefault();  // Prevent the click from going to the link

    $.ajax({
        url: wc_add_to_cart_params.ajax_url,
        method: 'post',
        data: { 
            'action': 'myajax'
        }
    }).done( function (response) {
          if( response.error != 'undefined' && response.error ){
            //some kind of error processing or just redirect to link
            // might be a good idea to link to the single product page in case JS is disabled
            return true;
          } else {
            window.location.href = SO_TEST_AJAX.checkout_url;
          }
    });

  });

});
like image 143
helgatheviking Avatar answered Sep 24 '22 07:09

helgatheviking