WordPress development – how to sort posts by “Last Modified” date

WordPress displays your posts chronologically by creation date out of the box. However, as a theme developer, you might want posts ordered by when they were last updated instead. In this guide, you’ll learn how to modify your home page to sort posts by “Last Modified” date, giving you better control over your content’s presentation. Add this code to your functions.php

function sort_homepage_posts_by_modified_date($query)
{
    // Apply only to the main query, not the custom queries
    if ($query->is_main_query()) {
        if (!is_admin() && $query->is_home()) {
            $query->set('orderby', 'modified');
            $query->set('order', 'DESC');
        }
    }
}

add_action('pre_get_posts', 'sort_homepage_posts_by_modified_date');