27. June 2011
von Blackbam

Recently, when working on a WordPress website for a huge amount of users, a customer was unsatisfyied with the WordPress backend search for users. The default backend search only is searching for your search string in usernames, but not for first name, last name or email of users.

 

As most WordPress projects are barely designed to have a huge amoung of users, this is not necessary in most cases. Anyway, the following code will help with this problem - add this to your functions.php-file and the WordPress user search will scan first name, last name and e-mail of every user.

 

Download the official WordPress Plugin

How the Plugin basically works (code overview of Version 1.2)
 
   // the actual improvement of the query
    function user_search_by_multiple_parameters($wp_user_query) {
        if(false === strpos($wp_user_query -> query_where, '@') && !empty($_GET["s"])) {

            global $wpdb;

            $uids=array();

   // get the custom meta fields to search
   $iusib_custom_meta = get_option('iusib_meta_fields');
   $iusib_cma = array_map('trim', explode(",",$iusib_custom_meta));

   $iusib_add = "";
   // the escaped query string
   $qstr = mysql_real_escape_string($_GET["s"]);
   
   // add all custom fields into the query
   if(!empty($iusib_cma)) {
    $iusib_add = " OR meta_key='".implode("' OR meta_key='",$iusib_cma)."'";
   }

            $usermeta_affected_ids = $wpdb -> get_results("SELECT DISTINCT user_id FROM ".$wpdb->base_prefix."usermeta WHERE (meta_key='first_name' OR meta_key='last_name'".$iusib_add.") AND LOWER(meta_value) LIKE '%".$qstr."%'");

            foreach($usermeta_affected_ids as $maf) {
                array_push($uids,$maf->user_id);
            }

            $users_affected_ids = $wpdb -> get_results("SELECT DISTINCT ID FROM ".$wpdb->base_prefix."users WHERE LOWER(user_nicename) LIKE '%".$qstr."%' OR LOWER(user_email) LIKE '%".$qstr."%'");

            foreach($users_affected_ids as $maf) {
                if(!in_array($maf->ID,$uids)) {
                    array_push($uids,$maf->ID);
                }
            }
   
            $id_string = implode(",",$uids);

            $wp_user_query -> query_where = str_replace("user_nicename LIKE '%".$qstr."%'", "ID IN(".$id_string.")", $wp_user_query -> query_where);
        }
        return $wp_user_query;
    }
Share

Dieser Eintrag wurde am 27. June 2011 um 23:23 in der Kategorie Plugins, WordPress, WP Scripts veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags: , , ,

Already 66 comments belonging to "WordPress improved user search (first name, last name, email) in backend":

Kommentare abonnieren (RSS) or URL Trackback

Jan Egbert   says:

on 05. July 2011 at 10:23 on clock


Thank you for sharing this snippet. Works great. It would be even better if it also searched for parts of emailadresses. Let's say I'm searching for 'fred' and there is an email address registered called 'amazingfred88@amazingemailaddress.com'. I tested a case like this and it doesn't find fred now unles I search the exact email address.

Blackbam     says:

on 14. July 2011 at 00:18 on clock


Hi there,
it took some time, but I found some time to improve the script today - now the search for e-mail addresses is working properly. Tell me if you experience any more bugs.

Jan Egbert   says:

on 24. August 2011 at 10:49 on clock


This response to your efforts to make this script even better took over a month. Sorry about that. But the script really rocks now. No more '0 results' when I know that there must be a user somewhere who's called Fred.;) Why don't you add this to the plugin repository. I could also do it for you if you want. In that case I'll give you all credits.

Blackbam     says:

on 30. August 2011 at 11:53 on clock ()


Hi Jan, I have requested to add the Plugin to the WordPress Plugin repository today, so it will hopefully be easy to find for everybody who wants to use it soon. It will be uploaded as soon as I get the confirmation.

Thank you for your help, if you want to and tell me your account name from wordpress.org, I can add you as a committer. Each of us can edit and improve the Plugin then, as well as answering questions.

Blackbam     says:

on 02. September 2011 at 18:14 on clock ()


The Plugin is officially uploaded to the WordPress Plugin directory by now:
http://wordpress.org/extend/plugins/improved-user-search-in-backend/

peeayoo   says:

on 07. September 2011 at 14:31 on clock ()


Hi Blackbam,

nice code. Small improvement from my perspective, either nothing critical.
instead of looping through all ids:

$id_string = "";
            $b = 0;
            foreach($uids as $aid) {
                if($b != 0) {
                    $id_string .= ",";
                }
                $id_string .= $aid;
                $b++;
            }


lets do it a little more fancy:

$id_string = implode("",$uids);


Thanks

p

Blackbam     says:

on 14. September 2011 at 13:21 on clock ()


The new Version of the Plugin includes the Code improvements suggested by peeayoo as well as the possibility to search for custom user meta fields.

bren   says:

on 30. September 2011 at 02:09 on clock


Hi Blackbam,

when trying to install the plugin WP reports an invalid header.
Posted by one user here
http://wordpress.org/support/topic/plugin-improved-user-search-in-backend-plugin-improved-user-search

Same problem here as well.
Tried installing manually and found that the folder and contents were there on FTP.
Tried all manner of hacking the header removed umlauts etc :o)
no luck :o(

Looking forward to a fix

thanks

Blackbam     says:

on 30. September 2011 at 14:02 on clock


Hey there, this problem was suddenly appearing and I really did not understand it, as I changed nothing and I do not know how this happend. I am searching for a solution currently. I suppose, I made the mistake which is talked about here on Stackoverflow. The repository is a bit confusing sometimes :-/ Hopefully I can fix this in a few days.

white_buddah   says:

on 11. November 2011 at 17:36 on clock


Hey Blackbam! I've find only your plugin for quick user's search and it's broken. This thing make me cry T_T I think that error happenes after Wordpress updates to 3.2.1 or smth Solution from StackOverflow doesn't work, I changed directory structure and put plugin manually via FTP but Wordpress don't even show plug in inactive plugins.. Dont know what to do. Maybe you know some alternative plugin with similar options? Thanx a lot!

Blackbam     says:

on 11. November 2011 at 18:45 on clock


Hey there, nobody can answer me how to repair the broken repository, which is really sad. I don not understand why they use it. It seems to me, as using the repository is more difficult than writing good Plugins.

But here is a solution to use the Plugin anyhow, with installing it manually:

1. Download this a fixed version of the Plugin

2. Go to Plugins -> Add new in your WordPress backend

3. Upload the fixed Plugin and activate it

4. Enjoy

This should work, as it has in the test. It is exactly the same Plugin, but with some naming changes so WordPress thinks its another one. Hope this helps!

white_buddah   says:

on 11. November 2011 at 19:02 on clock


Thank you for fast reply :)
Will try.

You did a great and useful job, Blackbam.

alicemdesign     says:

on 24. November 2011 at 11:33 on clock


Thanks for the plugin! I uploaded your fixed version, however when I tried to use it in the Users section, I get a blank page -- no results, no table, nothing. Any ideas?

Blackbam     says:

on 24. November 2011 at 16:34 on clock


Hey there,

the fixed version was tested with some WordPress installations, where problems didn't occur.

Where/when exactly did your error occur? When you submitted a keyword to search users?

Maybe more important: What version of WordPress do you use?

The Plugin hooks into the WordPress query, this might have changed with WordPress 3.3 (then this must be fixed) or is maybe different in older versions, so an invalid query might have been generated?

alicemdesign     says:

on 24. November 2011 at 21:05 on clock


Hi! I'm using WP 3.2.1 and the site is www.proacttraining.com. The error occured when I submitted a keyword (by first name) to search users in the back end (all users). It seems it just gets stuck. thanks!!

Joshua     says:

on 30. November 2011 at 19:49 on clock


Hey, I responded to your post on wordpress.org, but not sure if you saw it. I noticed that the svn version of your plugin contains old Mac-style line endings (\r), rather than Windows (\r\n) or unix (\n). When I manually converted it to unix-format, the plugin started working again. Your fixed version seems to have Windows-style endings. I am not sure if that is what is wrong with your plugin, but it might be worth changing to see if it fixes the issue.

Blackbam     says:

on 01. December 2011 at 00:35 on clock


@alicmedesign:

Hey there, as the Plugin seems to work for most users, it seems to be a specific problem regarding to your project. I recommend to to the following, which you should be able to do with some basic coding skills:

1. Take the function from this article and add it to your functions.php-file of your Theme

2. Add the following code in your functions.php, too:
add_action('pre_user_query', 'user_search_by_multiple_parameters');

3. You should remove the code for the meta fields.

If the Plugin is not working after doing this, there might be a problem with another Plugin. You can try deactivating all other Plugins and check if the Plugin is working now. If it is still not working, your WordPress installation might have been modified or is broken, as the Plugin works with other versions of WP 3.2.1.

Blackbam     says:

on 01. December 2011 at 00:44 on clock


@Joshua:

Hey Joshua, thanks a lot for your advice! I will check this problem soon.

Can you tell me, how you found out this thing with the line endings? What tool did you use?

Joshua     says:

on 05. December 2011 at 22:54 on clock


@Blackbam I do a lot of work with the vi editor on remote FreeBSD servers, which only supports the \n line endings, and shows special characters for the other line endings. If you use Windows for development, I tend to use Notepad++ (http://notepad-plus-plus.org/), which tells you what type of line ending the file has in the status bar.

Gennady   says:

on 08. December 2011 at 10:09 on clock


@Blackam, great plugin, although it didn't work for a multisite network out of the box. The thing is that when you use $wpdb->prefix the prefix is that of a blog (like wp_1_ or wp_2_ or wp_3_ and so on); multisite database tables do not have a users and usermeta table, they share the main site table with a wp_ (by default) prefix. So I had to change $wpdb->prefix to $wpdb->base_prefix which gives the base prefix in order for it to provide legal queries to existing tables. And yes, like @Joshua said, the plugin would not detect, I had to copy and paste the code between the tags into a new file.

Gennady   says:

on 08. December 2011 at 10:20 on clock


Another thing, David, that I personally did was lowercase the $_GET['s'] and LOWER() all query values in order to achieve case insensitive matching. LOWER(meta_value) LIKE... and LOWER(user_email) LIKE... etc. Also mysql_string_real_escape could only be done once in the beginning to save some cycles, except you have to keep the original query string intact in the final replace of the query_where part, otherwise it will not work. Again, good work! Thanks for this plugin.

Blackbam     says:

on 08. December 2011 at 11:48 on clock


Thank you, for your advices so far. The thing with the line endings did not fix the problem, and neither did fixing the tags in the repository so far. But I will keep trying, maybe I forgot something.

@Gennady: Your improvement ideas will be integrated into the next update, possibly as settings in the options page.

Joshua     says:

on 15. December 2011 at 01:47 on clock


@Blackbam I just did another checkout of your code from the svn repo, but it said nothing had been changed. How did you test this? If you would like, I might be able to try fixing the line endings on my side, and committing them to your wordpress plugin repository, although I am not sure if I can do that with my account or not.

Blackbam     says:

on 15. December 2011 at 02:31 on clock


@Joshua: Help would be really appreciated!

Tell me your WordPress.org Username and I will add you as a comitter to the Plugin. If you do not want to show it publicly here, send an email to admin@blackbam.at.

Joshua     says:

on 15. December 2011 at 21:52 on clock


@blackbam My wp username is jwhyatt

Blackbam     says:

on 16. December 2011 at 02:06 on clock


@Joshua: You have been added. You hopefully can connect to the repository now and try to fix it.

Joshua     says:

on 16. December 2011 at 18:56 on clock


@Blackbam I checked in a new version that seems to activate correctly now. Hopefully it won't cause you any more issues, and thanks for the great plugin.

Blackbam     says:

on 16. December 2011 at 21:54 on clock ()


Great, thanks to @Joshua the repository is repaired now!

So the new features will be implemented within some weeks now, too.

DW   says:

on 17. January 2012 at 19:46 on clock


Sorry for the newb question, but do I have to add this code if I've installed the plugin? Also, is there a specific place I should add the code within functions.php? Thanks dw

Blackbam     says:

on 17. January 2012 at 20:00 on clock


Hey, first of all you do NOT have to add any code to your functions.php if you install the Plugin. The code is published here, so that developers can see instantly how the Plugin works and possibly post improvement ideas.

Use the Plugin, not the code.

The code will not do anything if you paste it into your functions.php, unless you hook it into WordPress (Hook: 'pre_user_query') anyway.

Wassim   says:

on 04. March 2012 at 18:51 on clock


Hi, I think it is a great but when I try to add a Custom Meta Fields i.e. "GENDER" it becomes \'GENDER\' Is there a solution for this. Thx

Blackbam     says:

on 04. March 2012 at 20:18 on clock


Hey, because of some reason your blog added slashes to the options. I released a new version which validates the input of the meta fields, including stripslashes. Just download the new version and the problem should be gone.

Wassim   says:

on 05. March 2012 at 14:46 on clock


Hi Blackbam I downloaded the update, but now when I tried to use "GENDER", "BLOODTYPE", "LOH" I received the following error. Illegal characters in Custom Meta Fields detected, the string was sanitized.

Blackbam     says:

on 05. March 2012 at 17:04 on clock


Hello, you should not use quotes in your meta keys, as this can make problems with Queries. You are aware of, that these "keys" are the meta_key values of the wp_usermeta table right?

I do not think it is a good idea to have quoted meta keys, so i dissallowed meta keys containing non-alphanumeric characters, this is also for security reasons. Maybe this was a little bit to restrictive, so now the fields are escaped before the database query is done. There is no way around escaping quotes.

Wassim   says:

on 05. March 2012 at 18:20 on clock


Hi.. I used quotes because the following is mentioned Add custom user meta fields from your usermeta table for integration in the user search (e.g. "url", "description", "aim", or custom like "birthday") I have created extra fields with Cimy User Extra Fields, I have used the database names and the label names but none worked

Blackbam     says:

on 05. March 2012 at 21:49 on clock


Hey, there is quite an easy explanation for this. Cimy user extra fields is one of these Plugins creating own tables, instead of using the wp_usermeta table for storing user information. Therefore it is not possible for this plugin to find the user fields.

Maybe I will implement an extension for Cimy user extra fields soon, but the Plugins do not work together yet.

Wassim   says:

on 05. March 2012 at 23:21 on clock


N problem, thx for the reply

Rénald Casagraude   says:

on 11. May 2012 at 19:44 on clock


Hi,

Thanks for your plugin.

You should change tables references to increase compatibility :

$wpdb->base_prefix."users" should be $wpdb->users
$wpdb->base_prefix."usermeta" should be $wpdb->usermeta

I’ve notice some spaces around the "->" operator, I think that you should remove them.

Blackbam     says:

on 13. May 2012 at 23:24 on clock ()


Hey, thanks, your improvement suggestions have been implemented in the new version 1.2.3.

Ryan Hellyer     says:

on 01. August 2012 at 14:13 on clock


OMFG! YOU RULE!!!!! Seriously, this was driving me stark raving mad this afternoon. I'm been hunting through WordPress core attempting to figure out how to add this functionality and it has been driving me nuts! Thank you so much :)

rahal     says:

on 20. September 2012 at 11:57 on clock


Thank you for this! I've made a small improvement to be able to improve search users in network/users.php : I replaced :
$wp_user_query->query_where = str_replace("user_nicename LIKE '%".$qstr."%'", 
"ID IN(".$id_string.")", $wp_user_query->query_where);
By ( as it was easier than to propose a fix for wordpress ) :
$wp_user_query->query_where = str_replace( array("user_nicename LIKE '%".$qstr."%'" , 
"user_nicename LIKE '".$qstr."'" ), "ID IN(".$id_string.")", $wp_user_query->query_where);

Blackbam     says:

on 20. September 2012 at 21:20 on clock


Hey,

thank you for your improvement suggestion. I will implement and test this with the next Plugin update, so you can do further updates, too.

Greg   says:

on 24. September 2012 at 21:53 on clock ()


I'm totally in the dark on how to use this plug-in. I get that I don't also add the code to my Functions.php but after activating the plugin it does nothing different regarding searching for users. I see no hints on how I am to use the plug-in. I do see where to add custom fields but that's about it. Do I use the standard user serarch box? Do I wrap my search request in some form of tag, etc. Sorry to be so slow on this one.

Blackbam     says:

on 25. September 2012 at 09:27 on clock


Hello,

just install the Plugin from the public WordPress repository. The code here is just posted, as this article originally was about how to do it, and no Plugin existed yet.

The Plugin does exactly was the name says: Improved user search in backend.

1. Go to users
2. Use the standard search box and type in a keyword

Now all users matching the keyword will be listed. In standard WordPress unfortunatly, this search only looks for user nicename. With this Plugin, the search looks up most user fields, as well as user meta fields.

Tutahunia   says:

on 25. September 2012 at 12:47 on clock


I have install the plugin ...and also y creat the function en function.php ..but no result.

Blackbam     says:

on 25. September 2012 at 13:14 on clock


It works. Please read my previous answer.

Greg   says:

on 25. September 2012 at 19:14 on clock


Thanks. It does work now but didn't appear to when first installed. Maybe I had to exit and get back into the backend? I am getting one odd thing... some of the returned results appear on a second 1 user page and some return two users to a page. Some results say there are two results when in fact there is only one result that's duplicated. I can certainly work around this but I thought I'd pass this along. Thanks for the great function.

Blackbam     says:

on 25. September 2012 at 20:47 on clock


Well, this sounds alarming. But I cannot reproduce this bug in my current test environment currently and nobody else seems to experience this bug?

Maybe you can tell me a little bit more about your System. Are you using
- Multisite?
- WP version 3.4.2 or different?
- Plugins with extended user functions f.e. BuddyPress?
- unconventional database settings?

If you may find some concrete mistake in the code, please post it here.

Jessica Hung   says:

on 24. January 2013 at 02:42 on clock ()


Hi Blackbam, Thanks for this great plugin!! I was wondering if there's a way to include more fields? I'm currently using the Woocommerce plugin, which has customer information such as, address, phone numbers, etc... Is there a way to include those in the search as well? Thanks so much!!!

Blackbam     says:

on 24. January 2013 at 10:33 on clock ()


Hello

wonder why you did not find it yet. Go to Settings -> User Search in the WordPress Backend and insert the SLUGS of all the custom user meta fields you want to include in the user search. This will work for all user meta fields which are saved to the WP database correctly.

Donty   says:

on 19. February 2013 at 13:44 on clock ()


Hi Blackbam

Thanks for working on this, it does fit a surprising hole in sensible admin. Is the plugin updated on WP repository now? I have a 3..5.1 multisite that would benefit from this search enhancement but it is not yet working. Simply don't see any settings options or improvement on search eg search for email address.

Am I missing anything?

Thanks again

D

Blackbam     says:

on 19. February 2013 at 14:37 on clock ()


Hello Donty

this is the second request for full multisite support within two days I think it is time to implement it.

The Plugin currently IS working with multisite in the various subsites, but not in the screens showing all of the users (network administrator). I suppose that this is a different WordPress function. The Plugin will be updated in a few days/weeks with the aim of full multisite support.

Lee     says:

on 28. February 2013 at 23:11 on clock ()


I installed your plugin and I can't seem to get it to return a user by only a first or last name search.

I am running WP 3.5.1
Event Espresso 3.1.30.1
S2Member 130221
BuddyPress 1.6.4

Are any of these plugins incompatible with your plugin? Thanks.

Blackbam     says:

on 01. March 2013 at 11:17 on clock ()


Hello Lee, currently I do not KNOW about incompatibilities with any of this Plugins. But I can imagine very well that one of these Plugins, especially S2Member or BuddyPress are hooking into WordPress in a way, so the improved user search is not working.

Please can you deactivate each of this Plugins (preferrably in your test environment or maintenance mode) just to check if the improved user search is working and tell me which Plugin was responsible for the Problem? I can hopefully make an update to be compatible with this Plugin after some time then.

Lee     says:

on 01. March 2013 at 18:01 on clock ()


Black,

Thank you for the timely response! It is s2member that is blocking the use of your great plugin! We need s2member for the permissions it allows us to set individually. It's also a pretty popular plugin.

Basically s2member re formats the All Users dashboard to handle more data. I'm sure that's why there is a conflict.

Is this something you'll be looking into or putting on the back burner until there are more requests for it? Thank you.

Blackbam     says:

on 01. March 2013 at 20:37 on clock ()


Hey again I am going to have a look at S2Member compatibility at some time in the future, but currently my timetable is very full.

I think that s2member is reorganizing a lot of WPs' internal user structure, so this is why the Plugin is not working.

But you could take the code of the Plugin and try to integrate this with S2Member as the code of "Improved User Search" is quite simple. You just have to find the correct hook inside of S2Member.

marios     says:

on 29. March 2013 at 00:48 on clock ()


I have a mutlisite blog. I also use the cimy user extra fields.. I want to search users according to some filelds from this plugin. Is it possible?

Blackbam     says:

on 29. March 2013 at 15:27 on clock ()


Hello, yes I think this should be possible (as they are using the WordPress Standard to save additional user information). Just add the name/id of the user meta fields into the box of the "User Search" administration page.

kyle burnett     says:

on 23. October 2013 at 02:51 on clock ()


question... why join in all the meta keys via this method...

if(!empty($iusib_cma)) {
$iusib_add = " OR meta_key='".implode("' OR meta_key='",$wpdb->escape($iusib_cma))."'";
}

$usermeta_affected_ids = $wpdb->get_results("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE (meta_key='first_name' OR meta_key='last_name'".$iusib_add.") AND LOWER(meta_value) LIKE '%".$qstr."%'");


vs. just directly querying the meta table like so...

$usermeta_affected_ids = $wpdb->get_results("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE LOWER(meta_value) LIKE '%".$qstr."%'");

just curious about the theory there.

great plugin. super helpful.

Blackbam     says:

on 05. November 2013 at 21:17 on clock ()


@kyle: Because we want to have control over the meta keys to be searched in - otherwise the query might find users which we do not want to find because of the given search input.

Max   says:

on 07. November 2013 at 16:10 on clock ()


Hi Blackbam,

Any plan to update it for multisite?

I think that it could become a must have for any multisite admin since there's always a lot of user in there.

Thanks

Blackbam     says:

on 08. January 2014 at 20:51 on clock ()


Hello, sorry for the late answer. Yes, there is a plan for doing that, but currently time is missing.

Arial Burnz     says:

on 14. July 2014 at 20:27 on clock ()


I don't see anywhere on your website where I can make a donation. I used this plugin and am VERY grateful for it. I'd like to show you my support by making a donation for your efforts. Thank you!!

Blackbam     says:

on 15. July 2014 at 15:18 on clock ()


Hello Arial, thank you. You are right it I did not include any donation possibility for this Plugin maybe I will add this in some time. For some of my Plugins there is a donation possibility so if you donate for one of my other Plugins here I know that this donation is meant to be for the custom user search :-)

Ellis Benus Web Designer in Columbia MO     says:

on 30. July 2014 at 17:44 on clock ()


I just tried to download the plugin from the WordPress Repository but there is no PHP plugin file...? I downloaded the plugin to my machine and there is a readme file and language packs...? I'm very interested in using your plugin, could you help with this conundrum? :(

Blackbam     says:

on 31. July 2014 at 17:27 on clock ()


Hello Ellis thanks a lot for the tip - there was a SVN problem with the most recent update - fixed now!

Leave a comment:

Current day month ye@r *