Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add BOGO (Buy One Get One) Offer based on Specific Shipping Classes in WooCommerce?

As an online store owner, you can control promotional products by providing BOGO “Buy One Get One ” offers for specific shipping classes. The provided code snippet allows you to automatically add free products to the cart based on selected shipping classes.

function ts_aaptc_add_product_to_cart( $item_key, $product_id ) {
    $shipping_class_ids = array( 'light_items', 'heavy-items' ); // Add more shipping class slugs here

    $product_shipping_class = get_the_terms( $product_id, 'product_shipping_class' );

    if ( ! is_admin() && ! empty( $product_shipping_class ) ) {

        foreach ( $shipping_class_ids as $shipping_class ) {

            foreach ( $product_shipping_class as $term ) {

                if ( $term->slug === $shipping_class ) {

                    $free_product_id = 470; // Product Id of the free product which will get added to cart
                    $found = false;

                    // Check if product is already in cart
                    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
                        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                            $_product = $values['data'];
                            if ( $_product->get_id() == $free_product_id ) {
                                $found = true;
                                break;
                            }
                        }

                        // If product not found, add it
                        if ( ! $found ) {
                            WC()->cart->add_to_cart( $free_product_id );
                        }
                    } else {
                        // If no products in cart, add it
                        WC()->cart->add_to_cart( $free_product_id );
                    }

                    break 2; // Break out
   }
            }
        }
    }
}

add_action( 'woocommerce_add_to_cart', 'ts_aaptc_add_product_to_cart', 10, 2 );

Output

When products from specific shipping classes are selected, a free gift can be provided as per your choice. In the below output since the free product ID is set in the code, this specific product gets automatically added to cart when products from specific shipping class’ heavy items’ are added to the cart.

How to Add BOGO Offer based on Specific Shipping Classes in WooCommerce

You can also add free products to the cart based on the category of the items. Refer to this post to check on how to automatically add a product to your WooCommerce cart in 6 different conditions such as categories, cart total, add product on website visit, etc.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x