Retrieve category ID from one loop to use in another
-
Hello! I’m relatively new to the nitty-gritty of creating WordPress themes, and still have limited knowledge of PHP. So please excuse if this seems like an elementary question.
Essentially what I’m trying to do is manage two loops.
First loop. Retrieve the first post drawn from any of categories 1, 2 or 3. I’m doing that by this sort of structure:
<?php global $post; $myposts = get_posts('numberposts=1&cat=1,2,3); foreach($myposts as $post) : setup_postdata($post); ?> <!-- Stuff --> <?php endforeach; ?>
That’s all very straightforward.
Second loop. But what I want to do next is to detect whether the post from the first loop was in category 1. If it was in category 1, then my next loop will only display posts from categories 2 and 3.
<?php if ( CAT_ID OF THAT PREVIOUS POST = 1 ) { $secondloop = 'numberposts=1&cat=2,3'; } else { $secondloop = 'numberposts=1&cat=1,2,3'; } global $post; $myposts = get_posts($secondloop); foreach($myposts as $post) : setup_postdata($post); ?> <!-- Stuff --> <?php endforeach; ?>
What I’m not all that clear on is (1) how to retrieve the cat_id from the first loop, and (2) how to incorporate that into the if condition in the second loop.
- The topic ‘Retrieve category ID from one loop to use in another’ is closed to new replies.