One of the most powerful features of WP_Query is that it allows for us to create a type of mini-search engine within the context of our WordPress projects.
No, this isn’t as sophisticated as something or someone who’s actually in the search business, but you can create some pretty elaborate queries using WP_Query.
Conversely, you can also create some pretty simple queries that do a good job of returning a subset of data. For example, say you’re interesting in using WP_Query to search for a person. There may be a little bit of criteria that the user has to provide, but doing something like this is usually really easy.
For all intents and purposes, assume that you’re going to give the user the ability to search by:
- First name
- Last name
And it will be an OR
search. This means that the user can select from two mutually exclusive options (usually presented by radio buttons) that allow them to select the First Name, the Last Name, and then an input field for actually providing the field.
Using WP_Query to search for this kind of information is pretty straightforward:
- If the `$_POST` data contains information from the search field
- Read the type of data for which the user is user is searching (such as the First Name)
- Read the value of the data for which the user is searching (which is the actual field name)
- Construct the query
- Retrieve the results
- Loop through the results and display them to the user
It reads as if it’s a lot of steps, but it’s really not that bad (as I’ll show in just a minute). One extra thing that I usually like to do is to place a hidden input
element with a value that is sent along with the $_POST
request so that I can more easily check to see what’s being sent.
For example, I may have a hidden field with the name
attribute of member-field-searching
with a value of true
. Then, if that’s equal to true, I know that the end user is looking for a specific subset; otherwise, they may be looking to return all users.
Of course, the hidden field’s values can be set using JavaScript based on the user’s input, but that’s beyond the scope of what I’m trying to share.
So anyway, given a hidden field, a search field, and two radio buttons, here’s how you can use WP_Query to search for users that exist within the WordPress database:
From here, you can perform a foreach ( $users as $user ) {}
search and print the results to the screen however best suits your needs.
Note that the key to the above is that the user’s first and last name is stored as user meta data. If you were to expand this beyond just the first name and last name fields, then you’d need to make sure that you’re searching off the proper fields.
Leave a Reply
You must be logged in to post a comment.