The other day I ran into a situation where I needed to insert the results of a custom WordPress Loop within the results of another Loop.
Over on the Underground Film Journal, I create special Tag indexes for filmmakers that include their biography, filmography and list of WordPress articles I’ve written about them. While the list of articles is generated by the general WordPress Loop, the biography and filmography are generated by a special Loop of a Custom Post Type I’ve called “Filmmakers.”
What I wanted to do though was include a 2nd special Loop of just WordPress posts of videos by each filmmaker that I’ve featured on the site. However, due to the layout of the page, I needed to squeeze this 2nd Loop BETWEEN the biography and the filmography.
I was stumped on how to accomplish this for a few days until I came upon the realization that each filmmaker’s biography and filmography were single units of data that I could store in variables and then publish to the page basically wherever I wanted. So, I ended up running a special WP_Query Loop of the Custom Post Type, stored the biography and filmography in variables, then immediately closed this Loop.
While I did end up printing the biography right after the immediate close of this Loop, I could then run my 2nd special Loop of video posts, print those out, then go back and print out the filmography. You can see what I mean in the above screenshot. Also, here is the quickie Loop code I put together, which I have some notes about below:
<?php // Queries the Filmmakers Custom Post Type with current tag $tag = get_query_var('tag'); $filmmakers_query = new WP_Query( 'post_type=filmmakers&tag='.$tag ); // Start custom loop for Custom Post Type post if ($filmmakers_query->have_posts()) : while ( $filmmakers_query->have_posts() ) : $filmmakers_query->the_post(); //Store the filmmaker info in variables $filmmaker_bio = get_post_meta($post->ID, 'bio', true); $filmography = get_the_content_with_formatting(); endwhile; endif; wp_reset_postdata(); ?>
One special point of note is that, as you can see in the code, I store the filmmaker’s bio in a Custom Field that I code by hand with HTML tags, e.g. paragraph tags, “a href” links, italics, font bolding, etc.
But, the filmography, I store in the Content field. The drawback of storing WordPress Post data in a variable, is that all the HTML tags get stripped out. Luckily, someone came up with a function so that the HTML tags will indeed get stored in the variable, which you can grab here.
While this all works easily for me because I know ahead of time that the results of my Filmmakers Custom Post Type Loop will have exactly ONE post, I’m sure there are ways to use a foreach statement to store multiple posts in multiple variables. Just a thought.