Woocommerce Ajax以编程方式添加到购物车

时间:2022-10-25 10:01:35

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

此按钮位于我的homebage上,由页面构建器生成。我想要完成的是当有人点击按钮时,它会将它们带到结账处,并将产品添加到购物车。我知道这可以通过URL完成,但我需要让这个按钮做其他事情(客户的想法)。

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.

我是一个javascript noob,所以你能指出我正确的方向,或者给我一个暗示我做错了什么。

Thanks in advance!

提前致谢!

2 个解决方案

#1


4  

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

正如我在评论中提到的,你几乎可以借用核心WooCommerce功能。

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

首先,这是我们将尝试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.

其次,我们将加载我们的自定义脚本并传递重要的变量,例如admin ajax和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:

现在我们将编写我们的ajax回调函数,它几乎逐字地从WooCommerce核心中复制,只需进行一些小的修改:

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:

最后是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;
          }
    });

  });

});

#2


0  

You likely need to cancel/prevent the default action of clicking the link, and then redirect once the AJAX call finishes (this is just one way to do it):

您可能需要取消/阻止单击链接的默认操作,然后在AJAX调用完成后重定向(这只是一种方法):

jQuery(document).ready(function($){     
  $(".remove-all").click(function(e){
    e.preventDefault();  // Prevent the click from going to the link
    var $redirect = $(this).attr('href');        

    $.ajax({
        url: "wp-admin/admin-ajax.php",
        data: 'myajax',
        success: function () {
          window.location.href = $redirect;
        }
    });
  });
});

PHP

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

function myajax() {
    $product_id = 264;
    // Avoid using the global $woocommerce object
    WC()->cart->add_to_cart($product_id);
    die();
}

#1


4  

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

正如我在评论中提到的,你几乎可以借用核心WooCommerce功能。

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

首先,这是我们将尝试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.

其次,我们将加载我们的自定义脚本并传递重要的变量,例如admin ajax和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:

现在我们将编写我们的ajax回调函数,它几乎逐字地从WooCommerce核心中复制,只需进行一些小的修改:

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:

最后是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;
          }
    });

  });

});

#2


0  

You likely need to cancel/prevent the default action of clicking the link, and then redirect once the AJAX call finishes (this is just one way to do it):

您可能需要取消/阻止单击链接的默认操作,然后在AJAX调用完成后重定向(这只是一种方法):

jQuery(document).ready(function($){     
  $(".remove-all").click(function(e){
    e.preventDefault();  // Prevent the click from going to the link
    var $redirect = $(this).attr('href');        

    $.ajax({
        url: "wp-admin/admin-ajax.php",
        data: 'myajax',
        success: function () {
          window.location.href = $redirect;
        }
    });
  });
});

PHP

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

function myajax() {
    $product_id = 264;
    // Avoid using the global $woocommerce object
    WC()->cart->add_to_cart($product_id);
    die();
}