WooCommerce add_to_cart Shortcode – Product already in Cart

I’ve added the WooCommerce shortcode “add_to_cart” successfully on a custom post type page.

[add_to_cart id=”510″]

Read More

If there is nothing in the cart, it redirects to the shopping cart adding the product as intended. However, if the product is already in the cart and the user click the button on the custom post type page, it redirects back to itself.

The user can’t add more than one of a given item to the cart. How can I check to see what’s in the cart, so that if the user clicks the button it will redirect to the shopping cart if that product is already in there? Don’t need any error message to come up like on the standard WooCommerce product page.

Thanks in advance for any ideas!

Aaron

Related posts

Leave a Reply

2 comments

  1. Try this,

    When the users clicks on the button you can check the current cart item with this code.

    global $woocommerce;
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
    
      if($cart_item['product_id'] == $your_product_id){
       //the item already added to the cart
     }
    } 
    

    This will iterate the all items in the cart also if you want to add a product forcefully to the cart just need this,

    $woocommerce->cart->add_to_cart($product_id,$qty);
    

    Hope its helps..

  2. I was looking for a way to add a cart button to the bottom of my product pages. In the end I added the following html code:

    <form class="cart" method="post" enctype='multipart/form-data'>
        <button type="submit" name="add-to-cart" value="820" class="single_add_to_cart_button button alt">Add to basket</button>
    </form>
    

    The value is the product ID.

    Hope this helps someone with the same issue