在woocommerce中,当购物车为空时,ajax添加到购物车方法不添加,如果购物车包含某些内容,则我的ajax函数会添加,但如果购物车为空,则不会添加。没有错误。
这是link.PHP添加购物车功能:
function add_custom_product_meta() {
global $woocommerce, $wpdb;
$item_id = isset($_POST[\'item_id\']) ? apply_filters( \'woocommerce_add_to_cart_product_id\', absint( $_POST[\'item_id\'] ) ) : FALSE;
$quantity = empty( $_POST[\'quantity\'] ) ? 1 : wc_stock_amount( $_POST[\'quantity\'] );
$passed_validation = apply_filters( \'woocommerce_add_to_cart_validation\', true, $item_id, $quantity );
$product_status = get_post_status( $item_id );
$variation_id = isset($_POST[\'variation_id\']) ? $_POST[\'variation_id\'] : 0;
$atributes = isset($_POST[\'atributes\']) ? $_POST[\'atributes\'] : \'Small\';
$attribute_pa_macaroons = isset($_POST[\'attribute_pa_macaroons\']) ? $_POST[\'attribute_pa_macaroons\'] : FALSE;
if($attribute_pa_macaroons && $passed_validation && $woocommerce->cart->add_to_cart( $item_id, $quantity, $variation_id, array( \'attribute_size\' => $atributes, "macaroons" => $attribute_pa_macaroons))){
//$added = $woocommerce->cart->add_to_cart( $item_id, $quantity, $variation_id, array( \'attribute_size\' => $atributes, "macaroons" => $attribute_pa_macaroons));
do_action( \'woocommerce_ajax_added_to_cart\', $item_id );
if ( get_option( \'woocommerce_cart_redirect_after_add\' ) == \'yes\' ) {
wc_add_to_cart_message( $item_id );
}
WC_AJAX::get_refreshed_fragments();
echo json_encode(array(
\'atributes\' => $atributes,
\'macaroons\' => $attribute_pa_macaroons,
\'product_added\' => TRUE,
\'ajax_complete\' => TRUE,
\'posted\' => isset($_POST[\'item_id\']) ? $woocommerce->cart : \'item_id is empty\'
));
wp_die();
}
echo json_encode(array(
\'product_id\' => FALSE,
\'product_added\' => FALSE,
\'ajax_complete\' => TRUE,
\'posted\' => $attribute_pa_macaroons
));
wp_die();
}
Javascript Ajax调用:
$.ajax({
type : \'post\',
dataType : \'json\',
url : woocommerce_params.ajax_url,
data : {
\'action\' : \'elephas_addtocart_box\',
\'item_id\' : itemID,
\'quantity\' : quantity,
\'variation_id\' : variathionID,
\'atributes\' : atributes,
\'attribute_pa_macaroons\' : itemData
}
})
.done(function(response){
if(response.ajax_complete){
document.location.reload(true);
}
})
.error(function(error){
console.log(error);
})
.always(function(response){
if(response.ajax_complete){
document.location.reload(true);
}
});