How to extend search for custom post types in WordPress admin

I recently had to extend the search to include custom fields in WordPress admin. I created a custom post type called “document” and a few custom fields such as “_file_name” and “_url”. Unfortunately, it’s not possible to search by custom field value in WordPress admin, so I had to hook into the native WordPress search and tweak it.

WordPress admin search

In order to change the search query, you need to hook into pre_get_posts action. The pre_get_posts action gives developers access to the $query object by reference (Read more at WordPress Codex).

WordPress admin search

Here’s the code. You can change $post_type and $custom_fields according your needs.

Join the Conversation

4 Comments

  1. Yes it seems to omit search by title or other fields.

    Is there a way to include existing search but ALSO look for custom fields and not JUST custom fields.

    Thanks.

  2. Thanks for your code. Here’s how I added the feature to search BOTH title and meta.

    Taken from here:
    https://wordpress.stackexchange.com/questions/78649/using-meta-query-meta-query-with-a-search-query-s/208939#208939

    Basically I just added the $query->set(‘_meta_or_title’, $search_term);
    and gave the actions priorities (sql has to be after).

  3. Great piece of code did just what I wanted. I added all my custom fields and now they are all searchable.

    $custom_fields = array(
    “grave_number”,
    “age_at_death”,
    “date_of_death”,
    “date_of_burial”,
    );

    But now I can’t search by Title or Name so really we haven’t extended the search facility……how can we get both to work and it will be perfect?

    Thank you.

Leave a comment

Your email address will not be published. Required fields are marked *