This is my 560th post since I started blogging in June 2007, Sometimes those old posts have useful information, but I want search results to show the newest posts first. Supposedly that is the WordPress default, but I noticed that searches were first displaying posts with the search term in the title, then sorting by date. For example, if you searched for “security”, you would first see some very old posts that have the word “security” in the title, followed by much newer posts that only have “security” in the body.
Here are the default sort results. Note the dates and the presence/absence of the word “security” in the title:
The extremely helpful Query Monitor plugin shows the SQL that generates those search results. Notice the ORDER BY clause:
I don’t know where ORDER BY wp_posts.post_title LIKE '%security%' DESC
is coming from, but that’s the reason title is sorted first. (WordPress ORDER BY is documented here. It explicitly says that the default is to order by Date. Enhancements are documented here, but I don’t see anything indicating that the default changed.)
Fortunately, it’s fairly straightforward to override this by adding the following functions.php in the child theme:
function my_order_by_date_only( $query ) {
$query->set( ‘orderby’, ‘date’ );
$query->set( ‘order’, ‘DESC’ );
}
add_action( ‘pre_get_posts’, ‘my_order_by_date_only’ );
With that in place, the results now look like this, showing five posts from this year first:
The SQL shows the simplified ORDER BY clause: