Let’s say you’re in the process of building some type of search mechanism using WP_Query and you want your users to be able to run the search using part of a string.

That is, let’s say that you’re searching Companies (which is a custom post type) and some of the company’s names is “Awesome Code.” The user doesn’t know this because you’ve built a huge database and have been wildly successful with your app.

So let’s say the user opts to try to run a search using the fragment of ‘awe’ or ‘some’ or ‘code’ or some fragment variation thereof – how are we supposed to be able to pull back results like that?

Substrings in WordPress

Depending on how your code is organized, you can use a comparison LIKE in your search clause. Sounds enough easy, right?

Your mileage may vary based on how the information is stored in the database and you may need to use the $wpdb object to run a direct query against the database, but I’ve found it really useful to keep track of certain things in the post meta data (or even the in user meta data, for that matter) for situations just like this.

Case in point: Let’s say that in addition to keeping track of Companies, you’re also going to keep track of Employees (which are basically users) who are associated with Companies and who have that relationship is maintained in the meta data.

So the next thing you want to do is be able to run a search off of the meta data using something like the following structure:

Obviously, this assumes that you know the meta key with which you’re working and that the value is likely coming from the search field as provided by the user, but the compare directive makes it easy to use a LIKE comparison rather than any of the others and is exactly how you go about pull information back from the database for which the search is basically a substring of the data.