Filter wp_query to search post title in function

If you want to do it via a single WP_Query call, then you can use the posts_clauses filter hook.

And the trick is, don’t set the part_number and product_variations_$_part_number meta queries via the meta_query arg, but use the above hook instead, i.e. manually build the SQL clauses.

Working Example

Note: In your led_search_function() code, the above-mentioned meta queries should first be removed.

// In the theme's functions.php file, or somewhere in your plugin:
function my_posts_clauses( $clauses, $query ) {
    $part_number = $_POST['part_number'] ?? '';

    if ( strlen( $part_number ) && ! is_admin() ) {
        global $wpdb;

        $part_number2 = '%' . $wpdb->esc_like( $part_number ) . '%';

        $clauses['join'] .= " INNER JOIN $wpdb->postmeta my_mt1 ON {$wpdb->posts}.ID = my_mt1.post_id";

        // Search in the metadata part_number.
        $where = $wpdb->prepare( "(my_mt1.meta_key = 'part_number'
            AND my_mt1.meta_value LIKE %s)", $part_number2 );

        // Search in the metadata product_variations_$_part_number.
        $where .= $wpdb->prepare( " OR (my_mt1.meta_key = 'product_variations_\$_part_number'
            AND my_mt1.meta_value LIKE %s)", $part_number2 );

        // Search in post title.
        $where .= $wpdb->prepare( " OR ({$wpdb->posts}.post_title LIKE %s)", $part_number2 );

        $clauses['where'] .= " AND ( $where )";
        $clauses['groupby'] = "{$wpdb->posts}.ID";
    }

    return $clauses;
}

So add that function and then make the WP query like so (you could instead use a closure than adding/removing the filter like below, but that will be up to you on implementing it):

add_filter( 'posts_clauses', 'my_posts_clauses', 10, 2 );
$query = new WP_Query( $args );
remove_filter( 'posts_clauses', 'my_posts_clauses', 10 );

Leave a Comment