Get WordPress to Sort by Date Only without Title

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:

WordPress sort 1

The extremely helpful Query Monitor plugin shows the SQL that generates those search results. Notice the ORDER BY clause:

WordPress sort 2

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:

WordPress sort 3

The SQL shows the simplified ORDER BY clause:

WordPress sort 4

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.