Is there a way that I could control the rendering of an archive page that uses my own loop? I'd like to group the posts by a custom taxonomy, then sort them by date.

1 Answer 1


You should filter the default $query via callback hooked into pre_get_posts:

function wpse108983_filter_pre_get_posts( $query ) {
    // Make sure we're targeting
    // the main loop query, and
    // only in the archive context
    if ( $query->is_main_query() && is_archive() ) {
        // Add your query modifications here
        // For example, to sort by date:
        $query->set( 'orderby', 'date' );
add_action( 'pre_get_posts', 'wpse108983_filter_pre_get_posts' );

If you need to output multiple loops in order to group by taxonomy, you will, instead of the above approach, want to output custom loops via new WP_Query().

Assuming that you already know how to query terms for your taxonomy foobar, and have them in an array, $term_array:

// Loop through each term
foreach ( $term_array as $single_term ) {
    // Generate the term query
    $term_query = new WP_Query(
        'foobar' => $single_term,
        'orderby' => 'date'
    // Output the term query loop
    if ( $term_query->have_posts() ) : 
        while ( $term_query->have_posts() ) : 
            // Custom loop markup goes here
            // Use normal loop template tags, such as
            // the_content(), the_permalink(), etc
    // Important; don't forget this!
  • when is pre_get_posts best registered? I want to hook into the resulting query, modify it, and return different objects. Aug 7, 2013 at 1:30
  • pre_get_posts is an action, that allows you to do exactly what you say: hook into the query object, and modify it, before the query retrieves posts. You simply need to write a callback, and hook it into pre_get_posts. Aug 7, 2013 at 12:48
  • could you edit your answer and expand on that? where does the callback get written? does it go in a functions file or can i put it in a template file? Aug 7, 2013 at 12:51
  • Callbacks and add_action() calls always go in functions.php if part of a Theme. Aug 7, 2013 at 14:19
  • Thanks Chip! I was able to create the object structure i would need to loop over. Aug 17, 2013 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.