Skip to content

Instantly share code, notes, and snippets.

@yrosen
Created July 3, 2013 01:26
Show Gist options
  • Save yrosen/5914751 to your computer and use it in GitHub Desktop.
Save yrosen/5914751 to your computer and use it in GitHub Desktop.
Make WordPress look at specific post meta fields when doing a search
<?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