Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

wordpress - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  });

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...