• Resolved sebastijansakac

    (@sebastijansakac)


    Hi, I have problem adding items to cart on cart page.

    Wordpress version 5.5.3
    Woocommerce version 4.7.1

    This is the code I am using in functions.php
    If user is logged in or if is guest, I am getting cart_hash in response in JS.
    If user is not logged in add_to_cart() function returns $cart_item_key, but item is not added to cart and is not there even if I reload cart page.
    Hopefully someone can help me, because I have no idea where to find solution. I tried a lot of solutions found on google, but none is working.
    Thank you.

    function woocommerce_ajax_add_to_cart() {
    	$product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
    	$quantity          = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
    	$variation_id      = absint( $_POST['variation_id'] );
    	$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, $variation_id ) && 'publish' === $product_status ) {
    		do_action( 'woocommerce_ajax_added_to_cart', $product_id );
    		if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
    			wc_add_to_cart_message( array( $product_id => $quantity ), true );
    		}
    		WC_AJAX::get_refreshed_fragments();
    	} else {
    		$data = array(
    			'error'       => true,
    			'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
    		);
    		wp_send_json( $data );
    	}
    	wp_die();
    }
    add_action( 'wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart' );
    add_action( 'wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart' );
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Woocommerce add to cart AJAX not working for guest’ is closed to new replies.