Search code examples
phpwordpresswoocommercedefault

Woocommerce cart page default to one


I have my woocommerce page to sell a single product. I need to to go to the cart page with default value of 1 in cart page, so that when users click

www.test.com/cart

it never says "cart is Empty"! Any ways to do that? What do I need to do? Any ideas?


Solution

  • It sounds like you want to add a product to the user's cart even if they haven't actually added it themselves:

    So that when users click www.test.com/cart it never says "cart is Empty"

    For what it's worth, I don't think that's a fantastic idea from a UX point of view (or pretty much any other). However, it is possible.

    Be warned: This code is largely untested, and it's triggered to run on init (although it should only run each time the cart is visited). Generally, I would advise against this - but it should do what you want:

    function vnm_addThingToCart() {
    
        //  Check we're not in admin
    
        if (!is_admin()) {
    
            //  Only do this on the cart page
    
            if (is_page('cart')) {
                global $woocommerce;
    
                //  You're only selling a single product, so let's make sure we're not going to add the same thing over and over
    
                $myProductID = 22;  //  Or whatever
    
                $productToAdd = get_product($myProductID);
    
                //  Make sure the product exists
    
                if ($productToAdd) {
    
                    //  Make sure there's stock available
    
                    $currentStock = $productToAdd->get_stock_quantity();
    
                    if ($currentStock > 0) {
    
                        //  Add the product
    
                        $woocommerce->cart->add_to_cart($myProductID);
                    }
                }
    
            }
    
        }
    }
    
    add_action('init', 'vnm_addThingToCart');