Nested Loops and Custom WordPress Queries
read more

Nested Loops and Custom WordPress Queries

This post will cover a complex WordPress query and nested loop to output custom posts organized by a custom taxonomy. Let’s run through the specifics of this particular example. In the example, we’ll be organizing posts for our “Movie” post type by the years they were created, which is a custom taxonomy called “movie years”.

1. Create a custom post type with a name of movie.
2. Create a custom taxonomy for the movies post type and call it movie_years.
3. Create a custom archive template for the movie post type.
4. Retrieve every available year that contains a movie post.
5. Loop through every year and output a separate section for each.
6. Create a new WP_Query instance to pull posts from each year.
7. Loop through each year’s query to output the appropriate posts, organized by ascending title.

Before starting, I’ll be using the Genesis Framework so my code will be specific for Genesis. However, the loops and queries are universal and can be used in any WordPress theme. By the time we’re finished, the archive page will look something like this: