Php 仅显示第一篇文章的WordPress类别
我在一个页面上显示了来自父类别(“我们服务的地方”)的3篇最新帖子。在这个父类别中,我有6个按区域命名的其他类别(“非洲”、“欧洲”、“亚洲”等)。该页面显示区域类别名称及其下方的帖子内容。这就是问题所在;在这3个最近的职位中,有时会有2个来自同一区域类别。当这种情况发生时,我需要页面只显示该类别中第一篇文章的区域类别。希望这段代码能解释我要做的事情:Php 仅显示第一篇文章的WordPress类别,php,wordpress,Php,Wordpress,我在一个页面上显示了来自父类别(“我们服务的地方”)的3篇最新帖子。在这个父类别中,我有6个按区域命名的其他类别(“非洲”、“欧洲”、“亚洲”等)。该页面显示区域类别名称及其下方的帖子内容。这就是问题所在;在这3个最近的职位中,有时会有2个来自同一区域类别。当这种情况发生时,我需要页面只显示该类别中第一篇文章的区域类别。希望这段代码能解释我要做的事情: <div class="news"> <?php
<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>
编辑:我现在使用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";
};
当然不像我希望的那样干净或“正确”,但它现在正在工作…当您循环浏览帖子时,将您使用的类别保存到一个数组中,然后检查该数组以查看该类别是否已经存在
$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 />';
}
$used_categories=array()//可选,但为了清晰起见
foreach(最近发布的文章为$recent){
$category=获取_类别($recent[“ID”]);
$category\u name=$category[0]->cat\u name;
如果(!isset($used\u categories[$category\u name])){
//回显显示的类别名称
回显“.$category_name.”
;
//保存到已使用的类别。指定的值无关紧要
$used_categories[$categories_name]=true;
}
//无论哪种输出方式,都要将其从if中删除
回显“.$recent[“post_title”]。
”。$recent[“post_content”]。
”;
}
这太棒了!比我使用客户端脚本的解决方案要好得多。谢谢