I have a custom post type ‘events’, to which I have associated a custom taxonomy ‘calendar’. The calendar has 12 fixed terms, for each month of the year ( ‘august’, ‘october’, ‘november, etc.).

I’m in the process to make the archive page for the ‘events’ post type. I was thinking to display 12 different lists of max 10 posts each, for each month of the year == terms in the ‘calendar’ taxonomy.

Since this would be an archive page, WordPress would have already queried the database for ‘events’ post type. I was about to use query_posts to alter the main query, but I suddenly wondered if there was a better way to make a more optimized use of the default query. query_posts would essentially throw away the main query and with 12 lists to generate, it would cause more hits to the database.

Which is the best practice for this case?

Would you just run 12 instances of query_posts, one for each list, or you’d rather do something else, ie with pre_get_posts or something?

thanks for sharing your ideas

2 Answers
2

Don’t use query_posts(). Don’t modify the main loop query from within the template.

You may be able to get a single query to provide what you need (e.g. by filtering pre_get_posts and groupby), but more than likely, you will need to iterate 12 custom loops using WP_Query(). Perhaps something like this:

// Get all the months
$months = get_terms( $calendar );

// Set up the base query args
$events_query_args = array(
    'post_type' => 'events',
    'post_per_page' => 10,
    'tax_query' => array(
        array(
            'taxonomy' => 'calendar',
            'field' => 'slug',
            'terms' => ''
        )
    )
);

// Loop through the months, and
// output a custom query and loop
// for each
foreach ( $months as $month ) {

    // Add $month to the query args
    $events_query_args['tax_query']['terms'] = $month['slug'];

    // Build the query
    $events_query = new WP_Query( $events_query_args );

    // Open the query loop
    if ( $events_query->have_posts() ) : while ( $events_query->have_posts() ) : $events_query->the_post();

        // YOUR LOOP CODE GOES HERE

    // Close the loop
    endwhile; endif;

    // Clean up
    $events_query = null;
    wp_reset_postdata()
}

You’ll have to add the actual Loop output markup, of course.

Leave a Reply

Your email address will not be published. Required fields are marked *