1
votes

I'm displaying the 3 most recent posts from a parent category ("Where We Serve") on a page. Within that parent category, I have 6 other categories named by regions ("Africa", "Europe", "Asia", etc.). The page displays the region category name, and the post content below it. Here's the catch; of these 3 most recent posts, sometimes there will be 2 from the same region category. When that happens, I need the page to show the region category for ONLY the first post from that category. Hopefully this code explains what I'm trying to do:

            <div class="news">
                <?php
                $args = array( 'numberposts' => '3', 'category' => 9 );
                $recent_posts = wp_get_recent_posts( $args );
                foreach( $recent_posts as $recent ){
                    $category = get_the_category($recent["ID"]);
                    if(
                        $category == //any previous post's category on this page
                    ){
                        //echo the post WITHOUT the category name displayed
                        echo '<h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
                    }
                    else{
                        //echo the post WITH the category name displayed
                        echo '<h1>'.$category[0]->cat_name.'</h1><br><h2>'.$recent["post_title"].'</h2><br>'.$recent["post_content"].'<br>';
                    }

                }
                ?>
            </div>

I don't know how to test for other posts' categories on that page.

2

2 Answers

1
votes

As you loop through the posts, save the categories you have used to an array, then check that array to see if the category already exists.

$used_categories = array(); //optional, but for clarity
foreach( $recent_posts as $recent ){
    $category = get_the_category($recent["ID"]);
    $category_name = $category[0]->cat_name;
    if(!isset($used_categories[$category_name])){
        //echo the category name displayed
        echo '<h1>'.$category_name.'</h1><br />';
        //save to used categories. Value assigned doesn't matter
        $used_categories[$category_name]=true;
    }
    //You are outputting this either way, so take it out of the if
    echo '<h2>'.$recent["post_title"].'</h2><br />'.$recent["post_content"].'<br />';
}
0
votes

EDIT: I'm now using Eric G's method.

I wasn't able to get this to work with PHP. I ended up using this javascript at the bottom of the page:

var regionName = document.getElementsByTagName("h1");
if(regionName[1].innerHTML == regionName[0].innerHTML){
    regionName[1].style.display="none";
};
if(regionName[2].innerHTML == regionName[1].innerHTML){
    regionName[1].style.display="none";
};

Definitely not as clean or "correct" as I was hoping, but it's working for now...