Say what you will about the built in WordPress search functionality – sure, it could stand to be improved (personally I’m a fan of SearchWP) – but not all projects warrant the same requirements, right?

Sometimes, the built-in search functionality works just fine out-of-the-box. It gets a little more involved if you start introducing, say, custom taxonomies or custom post types, though.

That is, say you’re working on a project or have a client who needs help with modifying the built in search functionality so that it allows for searching custom post types. There’s actually a lot of flexibility provided in how you tailor the search results, but for this case it’s pretty easy.

Searching Custom Post Types

Let’s say that you want to search posts, pages, and a custom post type called reviews. In order to make this change, you’ll need to add a filter to the pre_get_posts hook that allows you to modify the specified query to include said post type.

For example, let’s say the post type has an ID of review. Here’s how you’d go about doing it:

Straightforward, isn’t it?

Simply put, check to see if the specified query is a search query. If so, then modify the post type argument and return it to the caller; otherwise, return from the function without modifying the query.

Category:
Notes
Tags:

Join the conversation! 2 Comments

  1. A couple things that have always bitten me when using this hook, as it affects every WP_Query not just the main one:

    Check if we’re in the admin, and bail if so, as you normally don’t want to affect the query running in the admin.


    if ( is_admin() ) {
    return;
    }

    Check whether we’re running the main query on the page, and if not, bail:


    if ( ! $query->is_main_query() ) {
    return;
    }

    • Yes – both of these are great points to add. Even consolidating them into a single conditional and placing them at the beginning of the function is a good idea:

      `

      if ( is_admin() || ! $query->is_main_query() ) {

      return;

      }
      `

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.