在woocommerce中,我们可以使用AJAX将多个产品添加到购物车中。以下是实现这个功能的代码示例:
add_action( 'wp_ajax_nopriv_add_to_cart_from_url', 'add_to_cart_from_url' ); add_action( 'wp_ajax_add_to_cart_from_url', 'add_to_cart_from_url' ); function add_to_cart_from_url() { if ( !wp_verify_nonce( $_REQUEST['nonce'], "add_to_cart_from_url_nonce")) { header( 'HTTP/1.1 503 Service Unavailable' ); exit; } if(isset($_REQUEST['product_ids']) && isset($_REQUEST['quantity']) && isset($_REQUEST['variation_id'])) { $product_ids = explode(',', $_REQUEST['product_ids']); $quantity = explode(',', $_REQUEST['quantity']); $variation_id = explode(',', $_REQUEST['variation_id']); for($i = 0; $i < count($product_ids); $i++) { $product_id = $product_ids[$i]; $quantity_id = $quantity[$i]; $variations_id = $variation_id[$i]; WC()->cart->add_to_cart( $product_id, $quantity_id, $variations_id ); } echo json_encode('Added to cart successfully'); } else { header( 'HTTP/1.1 503 Service Unavailable' ); exit; } die; }
function add_to_cart() { var product_id_string = ""; var quantity_string = ""; var variation_id = ""; jQuery(".product").each(function(index) { product_id_string += jQuery(this).data('product-id'); quantity_string += jQuery(this).find(".quantity").val(); variation_id += jQuery(this).find(".variation-id").val(); if(index < jQuery(".product").length - 1) { product_id_string += ","; quantity_string += ","; variation_id += ","; } });