Search code examples
wordpresswoocommercehook-woocommerce

Woocommerce Auto Add to Cart When Visiting product Page


How can I auto add to cart the product when user visit the product page, Eg: if a user visits www.example.com/product/abc product the function should automatically add the product to the user cart


Solution

  • You can use WC action hooks template_redirect to check if you are on a single product page. code will go in your active theme functions.php file.

    You can add product using two way

    using global $woocommerce;

    $quantity = 1;
    $woocommerce->cart->add_to_cart( get_the_ID(), $quantity );
    

    using WC()

    $quantity = 1;
    WC()->cart->add_to_cart( $product_id, $quantity );
    

    Complete code will look like this.

    add_action( 'template_redirect','add_product_into_cart_when_visit_product_page' );
    function add_product_into_cart_when_visit_product_page(){
        if ( class_exists('WooCommerce') ){
            if( is_product() ){
                global $woocommerce;
                $quantity = 1;
                $woocommerce->cart->add_to_cart( get_the_ID(), $quantity );
            }
        } 
    }
    

    Note - Remember it will add product every time you visit the page if you visit the same page every time then it will increment quantity. so if you want to add only one time then use the below code.

    add_action( 'template_redirect','add_product_into_cart_when_visit_product_page' );
    function add_product_into_cart_when_visit_product_page(){
        if ( class_exists('WooCommerce') ){
            global $woocommerce;
            if( is_product() ){
                $product_id = get_the_ID();
                if( !is_product_already_in_cart( $product_id ) ){
                    $quantity = 1;
                    $woocommerce->cart->add_to_cart( $product_id, $quantity );
                }
            }
        } 
    }
    
    function is_product_already_in_cart( $product_id ){
    
        $product_cart_id = WC()->cart->generate_cart_id( $product_id );
        $in_cart         = WC()->cart->find_product_in_cart( $product_cart_id );
      
        if ( $in_cart ) {
            return true;
        }
    
        return false;
    
    }