-
I noticed that one site’s archive is is not displaying based on the latest modified date. It’s running an Element with “Inherit query from template”. Do we need a functions snippet to display archives based on the last modified date (most recently modified displaying first)?
-
Alvind
Hi there,
Yes, you’ll need a snippet to modify the default query sorting. Try adding this:
function sort_by_modified_date($query) { // Only modify the main query on the frontend if (!is_admin() && $query->is_main_query()) { // Set orderby to 'modified' to sort by modification date $query->set('orderby', 'modified'); // Set order to 'DESC' for newest first $query->set('order', 'DESC'); } return $query; } add_action('pre_get_posts', 'sort_by_modified_date');
-
Thanks Alvind,
Can you tell me which is a better snippet. This one of the one you provided:
function wpb_sort_archives_by_modified_date( $query ) { if ( !is_admin() && $query->is_main_query() && $query->is_archive() ) { $query->set( 'orderby', 'modified' ); $query->set( 'order', 'DESC' ); } } // Hook into pre_get_posts to modify the archive query add_action( 'pre_get_posts', 'wpb_sort_archives_by_modified_date' );
-
Alvind
The code I provided changes the order of posts on every page of the website, displaying the most recently edited ones first.
The one you provided only affects list pages like category or tag archives, leaving the homepage unchanged. This is usually better because it scopes the change to where it’s needed while keeping the rest of the site working normally.
-
Perfect, thanks Alvind! Got it.
-
Alvind
You’re welcome!
- You must be logged in to reply to this topic.