使用AJAX在woocommerce中的“添加到购物车”按钮上添加其他产品

时间:2019-07-17 23:44:17

标签: jquery ajax woocommerce

因此,我们添加了通过代码放置在产品页面上的产品。单击“添加到购物车”按钮时,我试图通过AJAX执行添加操作,但是页面上的主要产品和新产品的添加似乎相互冲突,因为它已经启用了AJAX。有没有办法将它们结合起来?这是我添加额外产品的代码。

jQuery(document).ready( function($){



$('.single_add_to_cart_button').click(function(){

    var prodids = [];


    $('.checkbox-round').each(function(){
        var id = $(this).data('prod');
        prodids.push(id);
    })




     $.ajax({
         url: '?add-more-to-cart=' + prodids[0] + ',' + prodids[1],
         type: 'POST', 
         success: function(result){
            console.log("yesss");
            $.ajax($warp_fragment_refresh);
        }
    });




})



var $warp_fragment_refresh = {
    url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
    type: 'POST',
    success: function( data ) {
        if ( data && data.fragments ) {

            $.each( data.fragments, function( key, value ) {
                $( key ).replaceWith( value );
            });

            $( document.body ).trigger( 'wc_fragments_refreshed' );
        }
    }
};

});

在购物车网址中添加更多内容是功能文件中的自定义类,它可以很好地调用路线。

class add_more_to_cart {

private $prevent_redirect = false; //used to prevent WC from redirecting if we have more to process

function __construct() {
    if ( ! isset( $_REQUEST[ 'add-more-to-cart' ] ) ) return; //don't load if we don't have to
    $this->prevent_redirect = 'no'; //prevent WC from redirecting so we can process additional items
    add_action( 'wp_loaded', [ $this, 'add_more_to_cart' ], 21 ); //fire after WC does, so we just process extra ones
    add_action( 'pre_option_woocommerce_cart_redirect_after_add', [ $this, 'intercept_option' ], 9000 ); //intercept the WC option to force no redirect
}

function intercept_option() {
    return $this->prevent_redirect;
}

function add_more_to_cart() {
    $product_ids = explode( ',', $_REQUEST['add-more-to-cart'] );
    $count       = count( $product_ids );
    $number      = 0;

    foreach ( $product_ids as $product_id ) {
        if ( ++$number === $count ) $this->prevent_redirect = false; //this is the last one, so let WC redirect if it wants to.
        $_REQUEST['add-to-cart'] = $product_id; //set the next product id
        WC_Form_Handler::add_to_cart_action(); //let WC run its own code
    }
}
}
new add_more_to_cart;

0 个答案:

没有答案