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”.
- Create a custom post type with a name of movie.
- Create a custom taxonomy for the movies post type and call it movie_years.
- Create a custom archive template for the movie post type.
- Retrieve every available year that contains a movie post.
- Loop through every year and output a separate section for each.
- Create a new WP_Query instance to pull posts from each year.
- 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:
Create the Movie Custom Post Type and Custom Taxonomy
I’m going to assume you’ve either registered the movie post type and taxonomy or are comfortable with doing so. If you haven’t yet registered them, here’s a snippet you can use to get going right away. It includes the code to register both the movie custom post type and its movie_years taxonomy.
Create the Movie Archive Template
Since I’m using Genesis, I could just include a conditional in the following code and place it in my functions.php but, because I like to keep my functions file as lean as possible, I always prefer a separate template file so, for this tutorial, create a file called archive-movie.php and save it in your child theme’s root directory. Next, copy and paste this code to the file:
This file completes steps 4-7 and finishes off the basic requirements for our movie post type archive page. I’ve commented the code for additional help but feel free to ask if you have any questions.