[英]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.