wp admin – Extend user search in the Wp backend area on the users.php page to allow for searching by email domain and role from the “users search” input box

Question

I have been looking to extend the ability to search users in the backend for some time and have tried variations of several functions recommended in these articles and posts along with others not linked to shown below –

-https://wordpress.stackexchange.com/questions/339209/making-users-php-search-include-a-specific-user-meta-data-field-without-messing

-https://rudrastyh.com/wordpress/pre_user_query.html

-https://wordpress.stackexchange.com/questions/5811/how-to-search-all-user-meta-from-users-php-in-the-admin

I have used the function below as a template –

add_action('pre_user_query','rudr_extend_user_search');

function rudr_extend_user_search( $u_query ){
// make sure that this code will be applied only for user search
if ( $u_query->query_vars[‘search’] ){
$search_query = trim( $u_query->query_vars[‘search’], ‘*’ );
if ( $_REQUEST[‘s’] == $search_query ){
global $wpdb;

        // let's search by users first name
        $u_query->query_from .= " JOIN {$wpdb->usermeta} fname ON fname.user_id = {$wpdb->users}.ID AND fname.meta_key = 'first_name'";
        
        // you can add here any meta key you want to search by
        // $u_query->query_from .= " JOIN {$wpdb->usermeta} cstm ON cstm.user_id = {$wpdb->users}.ID AND cstm.meta_key = 'YOU CUSTOM meta_key'";

        // let's search by all the post titles, the user has been published
        $u_query->query_from .= " JOIN {$wpdb->posts} psts ON psts.post_author = {$wpdb->users}.ID";
        
        // what fields to include in the search
        $search_by = array( 'user_login', 'user_email', 'fname.meta_value', 'psts.post_title' );
        
        // apply to the query
        $u_query->query_where="WHERE 1=1" . $u_query->get_search_sql( $search_query, $search_by, 'both' );
    }
}

}

and also developed a function which is not working at all where I am attempting collect an email domain and role if they are entered into the search input as a string such as “@yahoo contributor” by imploding the string and then searching for the first value in the users table using a LIKE operator and perform a JOIN to the usermeta table where I would then search wp_capabilities for a value that is comparable to the role that would be the second value of the imploded string. I use the “pre_user_query” hook with my function but am only getting errors and feel I’m very far away from a solution. Any help or guidance is very appreciated.

0
Johnathan 2 months 2022-10-07T20:37:13-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse