WP_Query::parse_search_order
Generates SQL for the ORDER BY condition based on passed search terms.
Method of the class: WP_Query{}
No Hooks.
Returns
String. ORDER BY clause.
Usage
// protected - for code of main (parent) or child class $result = $this->parse_search_order( $query_vars );
- $query_vars(array) (required) (passed by reference — &)
- Query variables.
Notes
- Global. wpdb.
$wpdbWordPress database abstraction object.
Changelog
| Since 3.7.0 | Introduced. |
WP_Query::parse_search_order() WP Query::parse search order code WP 6.9.1
protected function parse_search_order( &$query_vars ) {
global $wpdb;
if ( $query_vars['search_terms_count'] > 1 ) {
$num_terms = count( $query_vars['search_orderby_title'] );
// If the search terms contain negative queries, don't bother ordering by sentence matches.
$like = '';
if ( ! preg_match( '/(?:\s|^)\-/', $query_vars['s'] ) ) {
$like = '%' . $wpdb->esc_like( $query_vars['s'] ) . '%';
}
$search_orderby = '';
// Sentence match in 'post_title'.
if ( $like ) {
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_title LIKE %s THEN 1 ", $like );
}
/*
* 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 ', $query_vars['search_orderby_title'] ) . ' THEN 2 ';
// Any word in title, not needed when $num_terms == 1.
if ( $num_terms > 1 ) {
$search_orderby .= 'WHEN ' . implode( ' OR ', $query_vars['search_orderby_title'] ) . ' THEN 3 ';
}
}
// Sentence match in 'post_content' and 'post_excerpt'.
if ( $like ) {
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_excerpt LIKE %s THEN 4 ", $like );
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_content LIKE %s THEN 5 ", $like );
}
if ( $search_orderby ) {
$search_orderby = '(CASE ' . $search_orderby . 'ELSE 6 END)';
}
} else {
// Single word or sentence search.
$search_orderby = reset( $query_vars['search_orderby_title'] ) . ' DESC';
}
return $search_orderby;
}