A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

WordPress: Custom post filters for Search

If you want to customize the query when doing a search in WordPress – when meta_queries are not enough.

The custom “WHERE” part of the query

function custom_where($where,$query) {
  global $wpdb;
 
  $new_where = " /*my new where*/ $wpdb->postmeta.meta_value LIKE '%".get_search_query()."%'";
  if (empty($where))
    $where = $new_where;
  else
    $where = "{$where} /*OR*/  OR {$new_where}";
 
  return $where;
}

The “DISTINCT” part

function search_distinct() {
  return "DISTINCT";
}

The custom “JOIN”

function custom_join($join) {
  global $wp_query, $wpdb;
  $join .= "INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
  return $join;
}

Putting them all up for the “pre_get_posts”

function filter_search($query) {
    if ($query->is_search) {
      $query->set('post_type', array('post', 'recipes'));
      add_filter('posts_where','custom_where');
      add_filter('posts_join', 'custom_join');
      add_filter('posts_distinct', 'search_distinct');
    }
    //var_dump($query);
    return $query;
};
 
add_filter('pre_get_posts', 'filter_search');
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>