WooCommerce Gift Product

How to grant the customer gift product when purchasing another product with common attributes?
Update the product category and id:

add_action( 'woocommerce_before_calculate_totals', 'wc_tights_bogo' );
add_filter( 'woocommerce_is_attribute_in_product_name', 'wc_hide_length', 10, 3 );

function wc_tights_bogo( $cart ) {
	if ( ( ! is_admin() || wp_doing_ajax() ) && 2 > did_action( 'woocommerce_before_calculate_totals' ) ) {
		$category_id = '136';
		$gift_product = '261';
		if ( ! isset( $_GET['gifts'] ) ) {
			$_GET['gifts'] = [];
		}
		if ( ! isset( $_GET['tights'] ) ) {
			$_GET['tights'] = [];
		}
		$data_store = WC_Data_Store::load( 'product' );
		foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
			if ( in_array( $category_id, wc_get_product_cat_ids( $cart_item['product_id'] ) ) ) {
				$product_atts = [
					'attribute_pa_leggings' => $cart_item['variation']['attribute_pa_leggings'],
					'attribute_pa_size' => $cart_item['variation']['attribute_pa_size'],
					'attribute_pa_color' => get_term_by( 'name', wc_get_product( $cart_item['product_id'] )->get_attribute( 'pa_color' ), 'pa_color' )->slug
				];
				$gift_variation = $data_store->find_matching_product_variation( wc_get_product( $gift_product ), $product_atts );
				$gift_cart_item_key = WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $gift_product, $gift_variation, $product_atts ) );
				if ( $gift_cart_item_key ) {
					$cart->set_quantity( $gift_cart_item_key, $cart_item['quantity'], false );
					$cart->get_cart()[ $gift_cart_item_key ]['data']->set_price( '0' );
					$_GET['gifts'][] = $gift_cart_item_key;
				} else {
					$cart->add_to_cart( $gift_product, $cart_item['quantity'], $gift_variation );
				}
			} elseif ( $cart_item['product_id'] == $gift_product ) {
				$_GET['tights'][] = $cart_item_key;
			}
		}
		// Removes unattached gifts but won't allow to purchase the product seperately, to allow it must add_to_cart the gift with special cart item meta for identification
		foreach ( wc_clean( array_diff( $_GET['tights'], $_GET['gifts'] ) ) as $cart_item_key ) {
//			$cart->remove_cart_item( $cart_item_key );
		}
	}
}

function wc_hide_length( $is_in_name, $attribute, $name ) {
	return false !== strpos( $name, 'shirt' ) && in_array( $attribute, [ 'short', 'long' ] );
}

Leave a comment

Your email address will not be published. Required fields are marked *