How to Sort Posts by Updated Date in WordPress

By default, WordPress sorts posts by their published date in descending order (newest first).

But if you want to sort posts by their updated date instead, it’s easy to do with a simple function and hook.

Key Takeaways

  • By default, WordPress sorts posts by their published date, but you can sort them by their updated date instead.
  • You can use the pre_get_posts action hook and a custom function to modify the query parameters and sort posts by their updated date.
  • Use the orderby parameter set to modified and the order parameter set to DESC to sort posts by their updated date in descending order.

Step-by-Step Guide to Sorting Posts by Updated Date

Here’s a step-by-step guide on how to sort posts by their updated date in WordPress:

Step 1: Create a Custom Function

Start by creating a custom function that modifies the query parameters for sorting posts by their updated date. You can use the pre_get_posts action hook to modify the query parameters before WordPress runs the main query.

Here’s an example of a custom function that sorts posts by their updated date:

<?php
function sort_posts_by_modified_date( $query ) {
    if ( !is_admin() && $query->is_main_query() ) {
        $query->set( 'orderby', 'modified' );
        $query->set( 'order', 'DESC' );
    }
}
add_action( 'pre_get_posts', 'sort_posts_by_modified_date' );
?>

In this function, we first check that we’re not in the WordPress admin area and that we’re working with the main query using the is_admin() and $query->is_main_query() methods respectively. Then we set the orderby parameter to modified and the order parameter to DESC to sort posts by their updated date in descending order.

Step 2: Hook the Custom Function into WordPress

Once you’ve created your custom function, you need to hook it into WordPress using the add_action() function. We’ll use the pre_get_posts action hook to modify the query parameters for sorting posts by their updated date.

Here’s an example of how to hook your custom function into WordPress:

<?php
add_action( 'pre_get_posts', 'sort_posts_by_modified_date' );
?>

This code should be added to your theme’s functions.php file or a custom plugin.

Step 3: Test Your Code

Finally, test your code to make sure posts are being sorted by their updated date in descending order. Go to your site’s front-end and view a page that displays your posts, and make sure the posts are sorted correctly.

Conclusion

By following the simple steps outlined above, you can easily sort your WordPress posts by their updated date in descending order. This can be a useful feature for content-rich sites with regular updates, as it allows visitors to quickly see the latest and most relevant content.