• Resolved wilkod

    (@wilkod)


    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.

Viewing 2 replies - 1 through 2 (of 2 total)
  • you could use
    $first_post_cats = wp_get_post_categories($post->ID);
    in the first loop, which will give you an array with all catgories of that first post.

    in the second loop, you could exclude these (i use the plural because in theory a post could have more then one category) from your given list of categories;

    example:

    $cats = array( 1, 2, 3);
    $second_loop_cats = array_diff($cats, $first_post_cats);
    $cat_ids = '';
    if($second_loop_cats) {
    $cat_ids = implode(', ',$second_loop_cats);
    $secondloop = 'numberposts=1&cat='.$cat_ids;
    }

    Thread Starter wilkod

    (@wilkod)

    Thanks alchymyth: that’ll work fine for me.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Retrieve category ID from one loop to use in another’ is closed to new replies.