Skip to content

Instantly share code, notes, and snippets.

@tarciozemel
Created January 11, 2013 14:46
Show Gist options
  • Save tarciozemel/4511190 to your computer and use it in GitHub Desktop.
Save tarciozemel/4511190 to your computer and use it in GitHub Desktop.
WordPress: busca com Custom Fields
//
// By default, WordPress comes with a handy search but it only search in post
// titles and contents. If you are working on a custom post type, you most
// probably using custom fields to store its attributes. For example, A
// Property custom post type would have address, city and state custom fields.
// You may have used WP_Query object with meta_query setup, But, it does not
// work. If you do not use “s” attribute, it will overwrite the default search
// and If you use it, it will not return the expected results. This snippet will
// use posts_clauses filter to inject the meta query that will combine with the
// WordPress’s default search parameter.
//
// http://wpdevsnippets.com/extend-search-include-custom-fields-without-plugin/
function custom_search_where($pieces)
{
// Filter to select search query.
if (is_search() && ! is_admin())
{
global $wpdb;
$custom_fields = array('field1','field2');
$keywords = explode(' ', get_query_var('s'));
$query = "";
foreach ($custom_fields as $field)
{
foreach ($keywords as $word)
{
$query .= "(({$wpdb->postmeta}.meta_key = '".$field."')";
$query .= " AND ({$wpdb->postmeta}.meta_value LIKE '%{$word}%')) OR ";
}
}
if ( ! empty($query))
{
// Add to where clause.
$pieces['where'] = str_replace("(((wp_posts.post_title LIKE '%", "( {$query} ((wp_posts.post_title LIKE '%", $pieces['where']);
// Add wp_postmeta join if it is not already added.
if (strpos($pieces['join'],'wp_postmeta') === FALSE)
{
$pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
}
}
}
return ($pieces);
}
add_filter('posts_clauses', 'custom_search_where', 20, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment