Created
July 3, 2013 01:26
-
-
Save yrosen/5914751 to your computer and use it in GitHub Desktop.
Make WordPress look at specific post meta fields when doing a search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('posts_where_request', function($where) use($wpdb, $wp) { | |
if(is_search()) { | |
// Change this as needed | |
$keys = implode("','", array('url', 'author', 'source', 'subtitle')); | |
// Search in meta fields as well: | |
$where .= " OR ({$wpdb->postmeta}.meta_key IN('{$keys}') AND {$wpdb->postmeta}.meta_value LIKE '%{$wp->query_vars['s']}%')"; | |
// Add in the postmeta table: | |
add_filter('posts_join_request', function($join) use($wpdb) { | |
return $join .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id "; | |
}); | |
// No duplicate results | |
add_filter('posts_distinct_request', function() { | |
return 'DISTINCT'; | |
}); | |
} | |
return $where; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment