0

I'm trying to display related posts on my taxonomy page, but not sure how to work out the second loop. I have shared taxonomys among posts, and on this page it shows post type A with tags "Light".

Some of the posts with tags "Light" are NOT post type A. So I have the following:

<?php $related = array(); ?>
<?php while (have_posts()) : the_post(); ?>
    <?php if(get_post_type() == 'Type_B' || get_post_type() == 'Type_C'){
        array_push($related, $post);
        continue;
    } ?>
<?php endwhile; ?>

This works fine. But then later down on the page where I want to loop type B and C I thought it would be simple to make a similar loop. But the wp_query array seems to be special? Even though my array contains posts.

if($related->have_posts()){
    while($related->have_posts()) { $related->the_post();
        print_r($post);
    }
}

I get the following error: Fatal error: Uncaught Error: Call to a member function have_posts() on array

I've tried $relatedList = new WP_query($related); but it's not right. Any tips?

Edit: Hm seems like I might have been going about this the wrong way. Where I have my second loop I still have access to the main loop, so I could just do an reveres post-if-check there. Is this what I should be doing? (code-standard-wise)

1

The main problem here is that $wp_query is not an array. It's and instance of WP_Query class. That's why it has some methods like have_posts, the_post, and so on...

On the other hand, your $related is normal PHP array, so it doesn't have any methods - so if you try to call any method, you're getting fatal error.

Since the posts are already added to $related array, the easies way to deal with them would be to just loop through that array:

if ( ! empty($related) ) {
    foreach ( $related as $post) {
        print_r($post);
        // you can't use template tags in here unless you use setup_postdata function
    }
}
  • I see, thank you! Of course, forgot the basic programming stuff right there smh. – Cammy May 27 '18 at 0:35

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.