Posted By

saturngod on 04/21/10


Tagged

wordpresssearch


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

creativeboulder
jbyerson


Search query in Wordpress


 / Published in: PHP
 

get from wp-include/query.php . Query class , line 1742

  1. // If a search pattern is specified, load the posts that match
  2. if ( !empty($q['s']) ) {
  3. // added slashes screw with quote grouping when done early, so done later
  4. $q['s'] = stripslashes($q['s']);
  5. if ( !empty($q['sentence']) ) {
  6. $q['search_terms'] = array($q['s']);
  7. } else {
  8. preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches);
  9. $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
  10. }
  11. $n = !empty($q['exact']) ? '' : '%';
  12. $searchand = '';
  13. foreach( (array) $q['search_terms'] as $term) {
  14. $term = addslashes_gpc($term);
  15. $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
  16. $searchand = ' AND ';
  17. }
  18. $term = $wpdb->escape($q['s']);
  19. if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
  20. $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
  21.  
  22. if ( !empty($search) ) {
  23. $search = " AND ({$search}) ";
  24. if ( !is_user_logged_in() )
  25. $search .= " AND ($wpdb->posts.post_password = '') ";
  26. }
  27. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: creativeboulder on November 28, 2011

Nice snippet. Great basis for a good Search page. Thanks. (I had to revise a few little things there for WP3.3 but all looks good).

You need to login to post a comment.