<?php
/*add_filter( 'posts_search', 'dina_product_search_by_sku', 9999, 2 );
function dina_product_search_by_sku( $search, $wp_query ) {
   global $wpdb;
   if ( ! is_search() || ! isset( $wp_query->query_vars['s'] ) || ( ! is_array( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] !== "product" ) || ( is_array( $wp_query->query_vars['post_type'] ) && ! in_array( "product", $wp_query->query_vars['post_type'] ) ) ) return $search; 
   $product_id = wc_get_product_id_by_sku( $wp_query->query_vars['s'] );
   if ( ! $product_id ) return $search;
   $product = wc_get_product( $product_id );
   if ( $product->is_type( 'variation' ) ) {
      $product_id = $product->get_parent_id();
   }
   $search = str_replace( 'AND (((', "AND (({$wpdb->posts}.ID IN (" . $product_id . ")) OR ((", $search );  
   return $search;   
}*/

add_filter( 'posts_search', 'dina_product_search_by_sku_partial', 9999, 2 );
function dina_product_search_by_sku_partial( $search, $wp_query ) {
    global $wpdb;

    // Only for search queries on products
    if ( ! is_search()
        || ! isset( $wp_query->query_vars['s'] )
        || ( ! is_array( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] !== "product" )
        || ( is_array( $wp_query->query_vars['post_type'] ) && ! in_array( "product", $wp_query->query_vars['post_type'] ) )
    ) {
        return $search;
    }

    $search_term = $wp_query->query_vars['s'];

    // Find product IDs that have SKU partially matching search term
    $product_ids = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT post_id 
             FROM {$wpdb->postmeta} 
             WHERE meta_key = '_sku' 
             AND meta_value LIKE %s",
            '%' . $wpdb->esc_like( $search_term ) . '%'
        )
    );

    if ( empty( $product_ids ) ) {
        return $search;
    }

    // If some of them are variations, include their parent ID
    $final_ids = [];
    foreach ( $product_ids as $pid ) {
        $product = wc_get_product( $pid );
        if ( $product && $product->is_type( 'variation' ) ) {
            $final_ids[] = $product->get_parent_id();
        } else {
            $final_ids[] = $pid;
        }
    }

    $final_ids = array_filter( array_unique( $final_ids ) );

    if ( empty( $final_ids ) ) {
        return $search;
    }

    // Inject product IDs into search SQL
    $ids_string = implode( ',', array_map( 'absint', $final_ids ) );
    $search = str_replace(
        'AND (((',
        "AND (( {$wpdb->posts}.ID IN ( {$ids_string} ) ) OR (( ",
        $search
    );

    return $search;
}
