通过Ajax添加自定义购物车项目数据添加到购物车

时间:2018-07-03 03:11:23

标签: php wordpress woocommerce

我正在使用此插件-Woocommerce PDF凭证-它开箱即用,效果很好。但是,在将我的主题的“添加到购物车”自定义为AJAXm后,它不会同时在迷你购物车和购物车页面中显示自定义数据。如果我恢复为默认的添加到购物车,效果很好,因此我的AJAX回调肯定存在错误。这就是我正在使用的:

// JS
$add_to_cart.on(‘click’, function(e) {
    e.preventDefault();
    var var_id = $(this).siblings(‘.variation_id’).val();
    var prod_id = $(this).siblings(‘input[name=“product_id”]‘).val();
    var item = {};
    var $variation_form = $( this ).closest( ‘.variations_form’ );
    var variations = $variation_form.find( ‘select[name^=attribute]’ );
    var mini_cart = $(‘.mini-cart-menu-item’);
    var mini_cart_contents = $(‘.widget_shopping_cart’);
    var url = ajax_obj.ajax_url;
    var data = {
        action: ‘nerb_ajax_add_to_cart_woo’,
        ‘product_id’: prod_id,
        ‘variation_id’: var_id,
        ‘variation’: item
    }

    variations.each( function()  {
        var $this = $(this);
        attributeName = $this.attr( ‘name’ );
        attributevalue = $this.val();
        item[attributeName] = attributevalue;
    });

    $.post( url, data, function(response) {         
        if (response) {
            mini_cart.html(response.fragments['a.cart-contents']);
            mini_cart_contents.html(
             response.fragments['div.widget_shopping_cart_content']
            );
        }       
    });
})

//PHP AJAX Callback
function nerb_ajax_add_to_cart_woo() {
    $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
    $product = wc_get_product( $product_id );
    $quantity = empty( $_POST['quantity'] ) ? 1 : apply_filters( 'woocommerce_stock_amount', $_POST['quantity'] );
    $variation_id = $_POST['variation_id'];
    $variations  = $_POST['variation'];
    $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );

    if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) ) {
        do_action( 'woocommerce_ajax_added_to_cart', $product_id );
        if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
            wc_add_to_cart_message( $product_id );
        }
        // Return fragments
        WC_AJAX::get_refreshed_fragments();
    } 
    die();  
}

add_action( 'wp_ajax_nerb_ajax_add_to_cart_woo', 'nerb_ajax_add_to_cart_woo' );
add_action( 'wp_ajax_nopriv_nerb_ajax_add_to_cart_woo', 'nerb_ajax_add_to_cart_woo' );

我认为这与我的JS函数中的“ var item = {}”有关。我想我可以选择自定义字段并将值分配给变量,但我认为如果将来添加新的自定义字段,则不必再次执行此操作。因此,我不确定要为“可变项”分配什么值

0 个答案:

没有答案