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 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 39 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.

Leave a comment: