plugin development – Why is WordPress wrapping search for users that looks like integers with asterisks and how do I fix it?


I’ve got a custom meta field for users called “user_ein”. It looks like an integer but is a string of number and it can start with the number “0”. I have the following code in a custom plugin so users can be searched on this number:

function search_by_user_ein( $query ) {
    if ( ! is_admin() || ! $query->query_vars['search'] ) {
        return $query;
    global $wpdb;
    $search = trim( $query->query_vars['search'] );
    // Uncomment next line to get search working on user_ein field
    // $search = trim( $search, '*' );
    $search="%" . $wpdb->esc_like( $search ) . '%';

    $query->query_from .= " LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb->usermeta}.user_id";

    $query->query_where .= $wpdb->prepare( " OR ({$wpdb->usermeta}.meta_key = 'user_ein' AND {$wpdb->usermeta}.meta_value LIKE %s)", $search );
    return $query;
add_filter( 'pre_user_query', 'search_by_user_ein' );

This didn’t work. If I put in “552398” into the search field, nothing was returned even though there is a user with the user_ein. After some head scraching, I dumped out the query and noticed that it was searching on *552398*. The search term was getting surrounded by asterisks.

To fix the problem, I added this code in after getting the search term from the $query object:

$search = trim( $search, '*' );

Things seem to work perfectly now but I’m worried there might be some unintended consequences. Is there a better fix than this?

StevieD 2 months 2023-02-06T00:40:06-05:00 0 Answers 0 views 0

Leave an answer