This customization leads to an effective promotional strategy as the parent product and the offered free product are from different categories. This also involves a way to introduce cross-selling products and make customers to explore another category that might be less popular or need attention. For example, If customers buy a pair of shoes from the Sneakers category, they get a Baseball Cap for free from the Accessories category.
function ts_add_product_cat( $cart_item_key, $product_id ) { $sports_category_id = 60; // Sports category ID $free_category_id = 16; // Category ID for free products $product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' ); if ( ! is_admin() && in_array( $sports_category_id, $product_cats_ids ) ) { // Get a free product from the specified category $free_product_id = ts_get_free_product_from_category( $free_category_id ); // If the free product is available, add it to the cart if ( $free_product_id ) { WC()->cart->add_to_cart( $free_product_id ); } } } add_action( 'woocommerce_add_to_cart', 'ts_add_product_cat', 10, 2 ); function ts_get_free_product_from_category( $category_id ) { // Implement this function to dynamically get a free product ID from the specified category $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $category_id, ), ), ); $products_query = new WP_Query( $args ); if ( $products_query->have_posts() ) { $products_query->the_post(); $free_product_id = get_the_ID(); wp_reset_postdata(); return $free_product_id; } return null; // Return null if no free product is found }
Output
When a customer adds a pair of sneakers to their cart, the ‘ts_get_free_product_from_category’ function takes a category ID as a parameter and queries the WordPress database to retrieve a single product ID from the specified category. If the product is found, as a bonus, a free product from the accessories category is also added to their cart.
Similarly, you can also automatically add free product for more number of categories. Check out this guide that will help you to automatically add a product to your WooCommerce cart based on ‘N’ number of conditions.