Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a custom post type that includes many custom fields. I would like to add them as a search target to admin search.

Currently the admin search searches only the content and the title, I would like it to search these custom fields as well.

Is there a way to do that ?

share|improve this question
    
I have been looking for this same thing for ages. I needed to search properties by ref number in the wordpress admin. Finally I found this brilliant plug-in: http://wordpress.org/plugins/search-everything/ Check it out; it can search any field and custom field! –  Spanglish Webs Jun 27 '13 at 10:24

1 Answer 1

up vote 5 down vote accepted

It is possible, but you'll have to play a little bit with the actual query. As always, the furious posts_clauses filter comes to action:

function wpse_alter_posts_search( $pieces )
{
    global $wpdb;

    // Make the input save
    $search_string = like_escape( $_GET['s'] );

    // Your new WHERE clause
    $where  = $wpdb->prepare(
        "$wpdb->postmeta.%s LIKE %s",
        'YOUR_COLUMN', // Should match your col name 1)
        "%{$search_string}%"
    );

    // Not sure if this exactly the same on your install 2)
    $pieces['where'] = str_replace( 'AND (((', "AND ((({$where} ", $pieces['where'] );

    return $pieces;
}
add_filter( 'posts_clauses', 'wpse_alter_posts_search' );

NOTES

  1. Could be that you need to unserialize some parts to be search able.
  2. You better simply dump the $pieces to take a look into them, before altering the query (right after the $search_string was received).
share|improve this answer
    
Or posts_where :D –  Stephen Harris Mar 8 '12 at 18:15
    
@StephenHarris I personally prefer the »alltogether« posts_clauses filter. No need to remember those (imho unnecessary) other filters... –  kaiser Mar 8 '12 at 18:16
    
I guess like_escape should be a function that escapes the search string to like format. can you please add it ? I'me having problems with this... –  hannit cohen Mar 9 '12 at 13:20
    
Added like_escape()ed to the prepare(). And no: It doesn't reformat the input search string. It makes it just save for queries, like other esc_* functions do for other tasks. –  kaiser Mar 9 '12 at 13:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.