WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 1 down vote accepted

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!
share|improve this answer
when is pre_get_posts best registered? I want to hook into the resulting query, modify it, and return different objects. – Daniel A. White Aug 7 '13 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. – Chip Bennett Aug 7 '13 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? – Daniel A. White Aug 7 '13 at 12:51
Callbacks and add_action() calls always go in functions.php if part of a Theme. – Chip Bennett Aug 7 '13 at 14:19
Thanks Chip! I was able to create the object structure i would need to loop over. – Daniel A. White Aug 17 '13 at 19:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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