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> ';    } ?>

这显示了帖子,但我希望它也显示类别名称。

任何帮助都会很好,

感谢

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

我能够使用以下方法来实现这一点。

$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> ';
}

我能够通过使用以下内容获得一个列表,该列表显示类别,然后显示标题。

 <?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()?>

我从来没能让下面的代码在我的原始代码中工作。它总是显示为"array"或Null(我猜我只是不知道写它的正确方法)。如果我创建了一个帖子,只想显示类别,而不想显示其他内容,我就能让它显示类别。

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

我使用了Jacob的答案,但

    $cats[0]->name

给了我每个帖子数组中的第一个类别。我所做的调整是在代码中使用增量运算符,一切都很好。

一个非常简单的例子:

    $recent_posts = wp_get_recent_posts( $args );
                    foreach( $recent_posts as $recent ){
                        $i = 0;
                        $cats = get_the_category($recent["ID"]);
                        echo $cats[$i]->name;
                        $i++;
                    }
                    wp_reset_query();

最新更新