WooCommerce is very popular WordPress plugin which helps you convert your WordPress blog into an E-Commerce shop. We often do a lot of WordPress plugins and WooCommerce extensions at DigiMantra Labs and a special request from the client was to add a particular product to the cart as soon as user lands on the homepage.

I found the following code quite helpful, hope it helps you too as well. You have to paste this code in functions.php (located in your active theme directory) or you can also place this in a plugin form and you have to activate this plugin.

// add item to cart on visit
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        global $woocommerce;
        $product_id = 64;
        $found = false;
//check if product already in cart
        if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
            foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
// if product not found, add it
            if ( ! $found )
                $woocommerce->cart->add_to_cart( $product_id );
        } else {
// if no products in cart, add it
            $woocommerce->cart->add_to_cart( $product_id );

Hope this code snippet helps you and saves some useful time!

Stay Digified!!
Sachin Khosla

Share this post: