So i have some pages where i want to show my custom post type 'events' only by the last 5 posts (secondary query: WP_Query object) and some pages where i want to show all posts (for instance archive template as is_main_query). I hate duplicate code - but i cant seem to outthink a way to not write loop code, even though it should display same structure, in separate places.
For instance; in my loop.php file I loop through all main query posts with have_posts(). But in my secondary queries where I use WP_Query, I cant call that loop file because its not a main query. Then I'll have to look up that specific query with $secondary_query->have_posts(), so i end up writing loop code where i call WP_Query..

So to wrap it up :-) is there a way I dont know about to use my loop file on secondary queries??
This is kind of what I want to do:

$event_query = new WP_query($args);
get_template_part('loop', 'home'); //calling loop.php

Move the control structure outside the template file and just put the repeatable markup and template tags inside.

$event_query = new WP_query($args);
if( $event_query->have_posts() ){
    while( $event_query->have_posts() ){
        get_template_part('loop', 'home');
| improve this answer | |
  • Thanks Milo, was about to add that as it seems from the comment to my answer that there are a slight misunderstanding on the part of the OP – Pieter Goosen Feb 13 '15 at 15:36
  • 1
    Of course! That is what im looking for! Brilliant - thanks and have a nice weekend all of you! – Mac Luc Feb 13 '15 at 15:51
  • this should be marked as the answer.. ;) – Reigel Feb 13 '15 at 15:53
  • Good idea - done :-) – Mac Luc Feb 13 '15 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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