[英]display WordPress category for its first post only
我正在页面上显示父类别(“我们在哪里服务”)中的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>
我不知道如何测试该页面上其他帖子的类别。
当您遍历帖子时,将您曾经使用过的类别保存到数组中,然后检查该数组以查看类别是否已经存在。
$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 />';
}
编辑:我现在正在使用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";
};
绝对不像我希望的那样干净或“正确”,但是它现在正在起作用...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.