I have a conflict issue with 2 custom post types. I have a template file archive-media.php and have created the related 'media' custom post type. This all works well, however in the sidebar I have a list of events from a second (events) custom post type, which also works perfectly in every respect, including on this page, except when there are no media items (eg if i set them all to draft), strangely the events list shows no events ( if ( have_posts() ) fails ). I cant seem to figure out why. My loop on the archive page is fairly standard, and doesnt use WP_query or query posts, roughly it's:

<?php if(have_posts()) :  ?>                    
<?php while(have_posts()) : the_post(); ?> 
.... LOOP ...
<?php endwhile; else : ?>
..... No media items ....
<?php endif; ?>

The events list is generated via the following function ( I left the two arguments in to save dismantling the code entirely but they are not being used at the moment). Also I cant remember off hand why i was globalising $post, It's in the original code, but i've tried it both in and out and it makes no difference. Another thing I've tried is various placements of wp_reset_query and wp_reset_postdata

function display_events($events_shown, $days_historical){
  // global $post;

  $args =  array(
          'post_type' => 'events',
          'posts_per_page' => 5,
          'order' => 'ASC'        

  $events_query = new WP_Query( $args );

  if ( have_posts() ) : while ( $events_query->have_posts() ) : $events_query->the_post(); 


    endwhile;  else : 
    echo "no events";           

Also I created a third test custom post type and archive page and the exact same problem occurred when I was on that archive page, and adding a new media item did not fix the problem, however adding a new test custom post type did, so somehow the secondary query is getting influenced by the fact that there are no items of the custom post type of the template on which the page is running ( ie no media items when on archive-media or no test items when on archive-test )

EDIT I just realised I could take the archive pages out of the equation by renaming them so as to force archive.php to display the media archive instead. Doing this gave me the exact same result.


It's still early for me, but you need to check for if( $events_query->have_posts() ) : rather than if( have_posts ) : as the latter will be checking against the current post type and not your custom query.

  • Can't believe I missed that. Thanks. I was convinced it was something much more sinister to do with queries getting mixed up or something. – byronyasgur Mar 16 '12 at 15:25

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.