<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[25632] trunk/src/wp-includes: Order search results by relevance, rather than by date.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://core.trac.wordpress.org/changeset/25632">25632</a></dd>
<dt>Author</dt> <dd>nacin</dd>
<dt>Date</dt> <dd>2013-09-27 17:33:36 +0000 (Fri, 27 Sep 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>Order search results by relevance, rather than by date.

The ordering logic is as follows:
 * Full sentence matches in post titles.
 * All search terms in post titles.
 * Any search terms in post titles.
 * Full sentence matches in post content.

Each section and any remaining posts are then sorted by date.

Introduces some filters:
 * wp_search_stopwords, to filter stop words ignored in WHERE.
 * posts_search_orderby, to filter the ORDER BY when ordering search results.

props azaozz, wonderboymusic.
fixes <a href="http://core.trac.wordpress.org/ticket/7394">#7394</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesdeprecatedphp">trunk/src/wp-includes/deprecated.php</a></li>
<li><a href="#trunksrcwpincludesfunctionsphp">trunk/src/wp-includes/functions.php</a></li>
<li><a href="#trunksrcwpincludesqueryphp">trunk/src/wp-includes/query.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesdeprecatedphp"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-includes/deprecated.php (25631 => 25632)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-includes/deprecated.php     2013-09-26 16:37:06 UTC (rev 25631)
+++ trunk/src/wp-includes/deprecated.php        2013-09-27 17:33:36 UTC (rev 25632)
</span><span class="lines">@@ -3317,6 +3317,18 @@
</span><span class="cx"> function _save_post_hook() {}
</span><span class="cx"> 
</span><span class="cx"> /**
</span><ins>+ * Formerly used internally to tidy up the search terms.
+ *
+ * @access private
+ * @since 2.9.0
+ * @deprecated 3.7.0
+ */
+function _search_terms_tidy( $t ) {
+       _deprecated_function( __FUNCTION__, '3.5', '' );
+       return trim( $t, "\"'\n\r " );
+}
+
+/**
</ins><span class="cx">  * Check if the installed version of GD supports particular image type
</span><span class="cx">  *
</span><span class="cx">  * @since 2.9.0
</span></span></pre></div>
<a id="trunksrcwpincludesfunctionsphp"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-includes/functions.php (25631 => 25632)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-includes/functions.php      2013-09-26 16:37:06 UTC (rev 25631)
+++ trunk/src/wp-includes/functions.php 2013-09-27 17:33:36 UTC (rev 25632)
</span><span class="lines">@@ -3703,19 +3703,6 @@
</span><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> /**
</span><del>- * Used internally to tidy up the search terms.
- *
- * @access private
- * @since 2.9.0
- *
- * @param string $t
- * @return string
- */
-function _search_terms_tidy($t) {
-       return trim($t, "\"'\n\r ");
-}
-
-/**
</del><span class="cx">  * Returns true.
</span><span class="cx">  *
</span><span class="cx">  * Useful for returning true to filters easily.
</span></span></pre></div>
<a id="trunksrcwpincludesqueryphp"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-includes/query.php (25631 => 25632)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-includes/query.php  2013-09-26 16:37:06 UTC (rev 25631)
+++ trunk/src/wp-includes/query.php     2013-09-27 17:33:36 UTC (rev 25632)
</span><span class="lines">@@ -1290,6 +1290,14 @@
</span><span class="cx">   var $thumbnails_cached = false;
</span><span class="cx"> 
</span><span class="cx">  /**
</span><ins>+        * Cached list of search stopwords.
+        *
+        * @since 3.7.0
+        * @var array
+        */
+       private $stopwords;
+
+       /**
</ins><span class="cx">    * Resets query flags to false.
</span><span class="cx">   *
</span><span class="cx">   * The query flags are what page info WordPress was able to figure out.
</span><span class="lines">@@ -1470,6 +1478,10 @@
</span><span class="cx">          if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
</span><span class="cx">          if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
</span><span class="cx"> 
</span><ins>+               // Fairly insane upper bound for search string lengths.
+               if ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 )
+                       $qv['s'] = '';
+
</ins><span class="cx">           // Compat. Map subpost to attachment.
</span><span class="cx">          if ( '' != $qv['subpost'] )
</span><span class="cx">                  $qv['attachment'] = $qv['subpost'];
</span><span class="lines">@@ -1895,6 +1907,183 @@
</span><span class="cx">  }
</span><span class="cx"> 
</span><span class="cx">  /**
</span><ins>+        * Generate SQL for the WHERE clause based on passed search terms.
+        *
+        * @since 3.7.0
+        *
+        * @global type $wpdb
+        * @param array $q Query variables.
+        */
+       protected function parse_search( &$q ) {
+               global $wpdb;
+
+               $search = '';
+
+               // added slashes screw with quote grouping when done early, so done later
+               $q['s'] = stripslashes( $q['s'] );
+               if ( empty( $_GET['s'] ) && $this->is_main_query() )
+                       $q['s'] = urldecode( $q['s'] );
+               // there are no line breaks in <input /> fields
+               $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
+               $q['search_terms_count'] = 1;
+               if ( ! empty( $q['sentence'] ) ) {
+                       $q['search_terms'] = array( $q['s'] );
+               } else {
+                       if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
+                               $q['search_terms_count'] = count( $matches[0] );
+                               $q['search_terms'] = $this->parse_search_terms( $matches[0] );
+                               // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
+                               if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
+                                       $q['search_terms'] = array( $q['s'] );
+                       } else {
+                               $q['search_terms'] = array( $q['s'] );
+                       }
+               }
+
+               $n = ! empty( $q['exact'] ) ? '' : '%';
+               $searchand = '';
+               $q['search_orderby_title'] = array();
+               foreach ( $q['search_terms'] as $term ) {
+                       $term = like_escape( esc_sql( $term ) );
+                       if ( $n )
+                               $q['search_orderby_title'][] = "$wpdb->posts.post_title LIKE '%$term%'";
+
+                       $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
+                       $searchand = ' AND ';
+               }
+
+               if ( ! empty( $search ) ) {
+                       $search = " AND ({$search}) ";
+                       if ( ! is_user_logged_in() )
+                               $search .= " AND ($wpdb->posts.post_password = '') ";
+               }
+
+               /**
+                * Filter the search SQL that is used in the WHERE clause of WP_Query.
+                *
+                * @since 3.0.0
+                *
+                * @param string   $search Search SQL for WHERE clause.
+                * @param WP_Query $this   The current WP_Query object.
+                */
+               return apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
+       }
+
+       /**
+        * Check if the terms are suitable for searching.
+        *
+        * Uses an array of stopwords (terms) that are excluded from the separate
+        * term matching when searching for posts. The list of English stopwords is
+        * the approximate search engines list, and is translatable.
+        *
+        * @since 3.7.0
+        *
+        * @param array Terms to check.
+        * @return array Terms that are not stopwords.
+        */
+       protected function parse_search_terms( $terms ) {
+               $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
+               $checked = array();
+
+               $stopwords = $this->get_search_stopwords();
+
+               foreach ( $terms as $term ) {
+                       // keep before/after spaces when term is for exact match
+                       if ( preg_match( '/^".+"$/', $term ) )
+                               $term = trim( $term, "\"'" );
+                       else
+                               $term = trim( $term, "\"' " );
+
+                       // \p{L} matches a single letter that is not a Chinese, Japanese, etc. char
+                       if ( ! $term || preg_match( '/^\p{L}$/u', $term ) )
+                               continue;
+
+                       if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
+                               continue;
+
+                       $checked[] = $term;
+               }
+
+               return $checked;
+       }
+
+       /**
+        * Retrieve stopwords used when parsing search terms.
+        *
+        * @since 3.7.0
+        *
+        * @return array Stopwords.
+        */
+       protected function get_search_stopwords() {
+               if ( isset( $this->stopwords ) )
+                       return $this->stopwords;
+
+               /* translators: This is a comma-separated list of very common words that should be excluded from a search,
+                * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
+                * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
+                */
+               $words = explode( ',', _x( 'about,an,are,as,at,be,by,com,for,from,how,in,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with,www',
+                       'Comma-separated list of search stopwords in your language' ) );
+
+               foreach( $words as $word ) {
+                       $word = trim( $word, "\r\n\t " );
+                       if ( $word )
+                               $stopwords[] = $word;
+               }
+
+               /**
+                * Filter stopwords used when parsing search terms.
+                *
+                * @since 3.7.0
+                *
+                * @param array $stopwords Stopwords.
+                */
+               $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
+               return $this->stopwords;
+       }
+
+       /**
+        * Generate SQL for the ORDER BY condition based on passed search terms.
+        *
+        * @global wpdb $wpdb
+        * @param array $q Query variables.
+        * @return string ORDER BY clause.
+        */
+       protected function parse_search_order( &$q ) {
+               global $wpdb;
+
+               $search_orderby = '';
+
+               if ( $q['search_terms_count'] > 1 ) {
+                       $num_terms = count( $q['search_orderby_title'] );
+                       $search_orderby_s = like_escape( esc_sql( $q['s'] ) );
+
+                       $search_orderby = '(CASE ';
+                       // sentence match in 'post_title'
+                       $search_orderby .= "WHEN $wpdb->posts.post_title LIKE '%{$search_orderby_s}%' THEN 1 ";
+
+                       // sanity limit, sort as sentence when more than 6 terms
+                       // (few searches are longer than 6 terms and most titles are not)
+                       if ( $num_terms < 7 ) {
+                               // all words in title
+                               $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
+                               // any word in title, not needed when $num_terms == 1
+                               if ( $num_terms > 1 )
+                                       $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
+                       }
+
+                       // sentence match in 'post_content'
+                       $search_orderby .= "WHEN $wpdb->posts.post_content LIKE '%{$search_orderby_s}%' THEN 4 ";
+                       $search_orderby .= 'ELSE 5 END)';
+               } else {
+                       // single word or sentence search
+                       $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
+               }
+
+               return $search_orderby;
+       }
+
+       /**
</ins><span class="cx">    * Sets the 404 property and saves whether query is feed.
</span><span class="cx">   *
</span><span class="cx">   * @since 2.0.0
</span><span class="lines">@@ -2235,36 +2424,10 @@
</span><span class="cx">                  }
</span><span class="cx">          }
</span><span class="cx"> 
</span><del>-               // If a search pattern is specified, load the posts that match
-               if ( !empty($q['s']) ) {
-                       // added slashes screw with quote grouping when done early, so done later
-                       $q['s'] = stripslashes($q['s']);
-                       if ( empty( $_GET['s'] ) && $this->is_main_query() )
-                               $q['s'] = urldecode($q['s']);
-                       if ( !empty($q['sentence']) ) {
-                               $q['search_terms'] = array($q['s']);
-                       } else {
-                               preg_match_all('/".*?("|$)|((?<=[\r\n\t ",+])|^)[^\r\n\t ",+]+/', $q['s'], $matches);
-                               $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]);
-                       }
-                       $n = !empty($q['exact']) ? '' : '%';
-                       $searchand = '';
-                       foreach( (array) $q['search_terms'] as $term ) {
-                               $term = esc_sql( like_escape( $term ) );
-                               $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
-                               $searchand = ' AND ';
-                       }
</del><ins>+                // If a search pattern is specified, load the posts that match.
+               if ( ! empty( $q['s'] ) )
+                       $search = $this->parse_search( $q );
</ins><span class="cx"> 
</span><del>-                       if ( !empty($search) ) {
-                               $search = " AND ({$search}) ";
-                               if ( !is_user_logged_in() )
-                                       $search .= " AND ($wpdb->posts.post_password = '') ";
-                       }
-               }
-
-               // Allow plugins to contextually add/remove/modify the search section of the database query
-               $search = apply_filters_ref_array('posts_search', array( $search, &$this ) );
-
</del><span class="cx">           // Taxonomies
</span><span class="cx">          if ( !$this->is_singular ) {
</span><span class="cx">                  $this->parse_tax_query( $q );
</span><span class="lines">@@ -2461,6 +2624,25 @@
</span><span class="cx">                          $orderby .= " {$q['order']}";
</span><span class="cx">          }
</span><span class="cx"> 
</span><ins>+               // Order search results by relevance only when another "orderby" is not specified in the query.
+               if ( ! empty( $q['s'] ) ) {
+                       $search_orderby = '';
+                       if ( ! empty( $q['search_orderby_title'] ) && empty( $q['orderby'] ) )
+                               $search_orderby = $this->parse_search_order( $q );
+
+                       /**
+                        * Filter the ORDER BY used when ordering search results.
+                        *
+                        * @since 3.7.0
+                        *
+                        * @param string   $search_orderby The ORDER BY clause.
+                        * @param WP_Query $this           The current WP_Query instance.
+                        */
+                       $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
+                       if ( $search_orderby )
+                               $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
+               }
+
</ins><span class="cx">           if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
</span><span class="cx">                  $post_type_cap = 'multiple_post_type';
</span><span class="cx">          } else {
</span></span></pre>
</div>
</div>

</body>
</html>