首页 文章

仅显示第一篇文章的WordPress类别

提问于
浏览
1

我正在页面上显示来自父类别(“我们服务的地方”)的3个最新帖子 . 在该父类别中,我还有6个按地区命名的其他类别(“非洲”,“欧洲”,“亚洲”等) . 该页面显示区域类别名称以及其下方的帖子内容 . 这是捕获;在这3个最近的帖子中,有时会有2个来自同一地区的类别 . 当发生这种情况时,我需要页面仅显示该类别中第一个帖子的区域类别 . 希望这段代码解释我正在尝试做什么:

<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>

我不知道如何在该页面上测试其他帖子的类别 .

2 回答

  • 0

    在遍历帖子时,将已使用的类别保存到数组中,然后检查该数组以查看该类别是否已存在 .

    $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>
    '; //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>
    '.$recent["post_content"].'
    '; }
  • 1

    编辑:我现在正在使用Eric G的方法 .

    我无法使用PHP . 我最终在页面底部使用了这个javascript:

    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";
    };
    

    绝对不像我希望的那样干净或“正确”,但它现在正在工作......

相关问题