php - Hide auto added gift product from WooCommerce catalog

I have the following scenario that I can not solve, could you guide me, either with a plugin or from code?

I have the product A and the product B, which should not appear in the store nor can it be added individually as it is a gift.

If someone adds product A to the cart, then the system should add product B. It is like a BOGO, but the problem that I cannot solve is that of the free product that must be invisible and not allow to be purchased individually.

Answer

Solution:

Based on Auto add to cart a Gift product variation programmatically in WooCommerce? answer code, here is the complete way to auto add a hidden gift product when a specific product is added to cart:

// Auto add a hidden gift product to cart based on sprcific product
add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_gift_to_cart' );
function wc_auto_add_gift_to_cart( $cart ) {
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    $required_product_id = 37; // The required product Id for a gift
    $product_gift_id     = 53; // The gift product Id

    $has_required = $gift_key = false; // Initializing

    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Check if required product is in cart
        if( in_array( $required_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
           $has_required = true;
        }
        // Check if gifted product is already in cart
        if( in_array($product_gift_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
           $gift_key = $cart_item_key;
        }
    }

    // If gift is in cart, but not the required product: Remove gift from cart
    if ( ! $has_required && $gift_key ) {
        $cart->remove_cart_item( $gift_key );
    }
    // If gift is not in cart and the required product is in cart: Add gift to cart
    elseif ( $has_required && ! $gift_key ) {
        $cart->add_to_cart( $product_gift_id );
    }
}

// Hide gift product from catalog (shop and archive pages)
add_action( 'woocommerce_product_query', 'hide_gift_product_from_catalog' );
function hide_gift_product_from_catalog( $q ) {
    // Not in admin
    if ( ! is_admin() ) {
        $product_gift_id = 53;

        $q->set('post__not_in', array($product_gift_id) );
    }
}

// Redirect gift product single page to shop
add_action( 'template_redirect', 'redirect_gift_single_product_to_shop' );
function redirect_gift_single_product_to_shop() {
    $product_gift_id = 53;
    //
    if ( get_the_id() == $product_gift_id ) {
        wp_redirect( wc_get_page_permalink( 'shop' ) );
        exit;
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Related: Auto add to cart a Gift product variation programmatically in WooCommerce?

Source