Sort WordPress Posts by Modified Date using a URL Param
After updating a few older articles on this blog I have realized that it would be useful to provide a display where all my posts are sorted by last modified date instead of created date. I imagine it would just be a link that someone can click and it would change the WP query so that recently updated posts are displayed in descending order. Everything else stays the same. You can see it in action on my homepage and today I will cover how you can do that with two simple WordPress functions.
As you can see above, we also use the pre_get_posts function to alter the default WP Query which returns all posts by creation date. Inside, I use get_query_var to get the url param and verify that its value is updated, which means the user wants see the posts sorted in that order. The conditional also makes sure that our change the WP Query is only for the main query and not in admin dashboard. If those conditions are met, the code
$query->set( 'orderby', 'modified' ); takes care of sorting posts by last modified date.