2012-07-14 129 views
1

我試圖讓我最近發表的文章列表中也可看出他們是什麼類別的,現在我有WordPress的獲取最近的職位和顯示名稱和類別名稱

<?php $args = array( 'numberposts' => 30) ; 
$recent_posts = wp_get_recent_posts($args); 
foreach($recent_posts as $recent){ 
echo '<li> 
    <a href="'.get_permalink($recent["ID"]).'" title="Look'.esc_attr($recent["post_title"]).'" > '.$recent["post_title"].'</a> </li> '; } ?> 

這顯示了職位,但我希望它也顯示類別名稱。

任何幫助將是巨大的,

感謝

+0

我嘗試添加一個變量$貓但是當它顯示頁面它打印出陣列<?PHP的\t的$ args =陣列( 'numberposts'=> 10); $ cats = get_the_category(); \t $ recent_posts = wp_get_recent_posts($ args); \t的foreach($ recent_posts爲$近期){ \t回聲 '

  • '.$recent["post_title"].''。$貓。」
  • '; \t}?> – 2012-07-15 03:14:20

    回答

    2
    $cats = get_the_category($recent["ID"]); 
    $cat_name = $cats[0]->name; // for the first category 
    

    你可以試試這個循環裏面(如果你有多個類別)

    $cats = get_the_category($recent["ID"]); 
    foreach($cats as $cat) 
    { 
        echo $cat->name." "; 
    } 
    
    +0

    你能解釋一下嗎?我對PHP和wordpress很陌生。 – 2012-07-15 03:12:04

    +1

    '$ cats = get_the_category($ recent [「ID」]);'將在'foreach'循環中檢索與當前帖子相關的所有類別,並且該函數接受一個參數(可選)來確定帖子,然後返回一個對象數組,並使用另一個「foreach」循環,我們用它們之間的「空格」回顯所有類別。 [參考這裏](http://codex.wordpress.org/Function_Reference/get_the_category)。 – 2012-07-15 07:23:29

    0

    我能得到一個列表通過使用以下內容顯示類別,然後顯示標題。

    <?php 
        $recentPosts = new WP_Query(); 
        $recentPosts->query('showposts=30');?> 
    <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> 
    <?php the_category(" "); ?>-<a href="<?php the_permalink()?>"> <?php the_title(); ?></a> 
    <?php endwhile; ?><?php wp_reset_query()?> 
    

    我從來沒有能夠得到下面的代碼我原來代碼中的工作,它會一直顯示爲「陣列」或空(我猜我只是不知道把它寫在適當的方式)如果我創建了一個帖子,並且只想顯示其他類別,我就能夠顯示該類別。

    $cats = get_the_category($recent["ID"]); 
    foreach($cats as $cat){ 
    echo $cat->name." "; } 
    
    1

    我能夠得到這個使用以下工作。

    $cats[0]->name." " 
    

    所以在最近的帖子循環中,您可以使用它像這樣:

    $args = array('numberposts' => 5, 'category' => '4,5'); 
    $recent_posts = wp_get_recent_posts($args);  
    
    foreach($recent_posts as $recent){ 
        $cats = get_the_category($recent["ID"]); 
        echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'">' . $cats[0]->name." " . $recent["post_title"].'</a> </li> '; 
    } 
    
    0

    我使用雅科答案,但

    $cats[0]->name 
    

    給我從數組中第一類在每個帖子上。我做的調整是在代碼中使用增量運算符,一切都很好。

    一個更簡化的例子:

    ​​
    相關問題