How to amend built-in WordPress Queries before execution

I wanted to update the order of posts shown on a regular category/tag archive page. At first I thought I’d have to write my own custom query for that, which would have meant a great deal of fudging an existing template that worked fine as it was. All I wanted to do was to amend a single parameter of the existing query WordPress was generating under the hood.

Lo and behold, there’s the beautiful hook we can use for this very purpose: pre_get_posts(). This is fired after all parameters for a regular WordPress query are setup, but before the actual query is executed. That’s exactly what I needed!

Here’s what I could do:

// amend archive pages to show last updated posts first function guru_order_category_archives( $query ) { if ( ! is_admin() && $query->is_main_query() ) { // Not a query for an admin page. // It’s the main query for a front end page of your site. if ( is_category() || is_tag() ) { // It’s the main query for a category/tag archive. // Update parameters before query is executed $query->set( ‘orderby’, ‘modified’ ); } } } add_action( ‘pre_get_posts’, ‘guru_order_category_archive’ );

According to the documentation, we’ll first need figure out of this query is a front-page query, rather than an admin one. Great to know we could hook into that as well if necessary. Knowing that, we ask if this is a category or tag archive, and if so, update our parameters accordingly. I changed the orderby option, but any query parameter will work here.

That’s all there’s to it! Next time an archive page is displayed, the query becomes as custom as we want it to be.

Further Reading

You can leave a comment on my original post.