kisabelle

Add Custom Fields to Default Wordpress Search

Oct 31st, 2013
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.60 KB | None | 0 0
  1. function custom_search_where($pieces) {
  2.     // filter to select search query
  3.     if (is_search() && !is_admin()) {
  4.         global $wpdb;
  5.         $custom_fields = array('your_custom_field', 'your_other_custom_field');
  6.         $keywords = explode(' ', get_query_var('s'));
  7.         $query = "";
  8.         foreach ($custom_fields as $field) {
  9.              foreach ($keywords as $word) {
  10.                  $query .= "((mypm1.meta_key = '".$field."')";
  11.                  $query .= " AND (mypm1.meta_value  LIKE '%{$word}%')) OR ";
  12.              }
  13.         }
  14.         if (!empty($query)) {
  15.             // add to where clause
  16.             $pieces['where'] = str_replace("(((wp_posts.post_title LIKE '%", "( {$query} ((wp_posts.post_title LIKE '%", $pieces['where']);
  17.             $pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
  18.         }
  19.     }
  20.     return ($pieces);
  21. }
  22. add_filter('posts_clauses', 'custom_search_where', 20, 1);
  23.  
  24. /*
  25. ** Code from:
  26. ** http://wpdevsnippets.com/extend-search-include-custom-fields-without-plugin/
  27. */
  28.  
  29. // ******************************************************
  30. // IMPORTANT: prevent duplicate posts being returned
  31. // ******************************************************
  32. function websmart_search_groupby( $groupby ) {
  33.         global $wpdb;
  34.         if( is_search() && !is_admin()) {
  35.                 $groupby = "$wpdb->posts.ID";
  36.         }
  37.         return $groupby;
  38. }
  39. add_filter('posts_groupby', 'websmart_search_groupby' );
  40.  
  41. /*
  42. ** Code from:
  43. ** http://websmartdesign.co.nz/searching-structured-post-data-with-wordpress/
  44. */
Advertisement
Add Comment
Please, Sign In to add comment