Data, Maps, Usability, and Performance

Sort WordPress Posts by Modified Date using a URL Param

Last updated on August 3, 2016 in Development

List Posts by Recently Updated in WordPress

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.

Somewhere in your template you need to create a link with a query or url parameter. You can hardcode it ( or build it with add_query_arg. I have built it here via JavaScript. The end result is that the user lands on a page where that query parameter and value (sortby=modified) is in the url. Next, in functions.php, we add that query parameter to the WP_Query using the query_vars filter.

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.

Tags: ,

Facebook Twitter Hacker News Reddit More...