【问题标题】:Wordpress get recent posts and display title and category nameWordpress 获取最近的帖子并显示标题和类别名称
【发布时间】:2012-07-14 23:03:51
【问题描述】:

我正在尝试列出我最近发布的帖子,同时显示他们现在属于哪个类别

<?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 但是当它显示页面时它打印出数组 10) ; $cats = get_the_category(); $recent_posts = wp_get_recent_posts($args); foreach( $recent_posts as $recent ) { echo '
  • '.$recent["post_title"].' '.$cats.'
  • '; } ?>

标签: wordpress categories


【解决方案1】:
$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." ";
}

【讨论】:

  • 你能解释一下吗?我对 php 和 wordpress 很陌生。
  • $cats = get_the_category($recent["ID"]); 将在foreach 循环中检索与当前帖子相关的所有类别,并且该函数接受一个参数(可选)来确定帖子,它获取类别然后作为结果返回一个对象数组并使用另一个foreach 循环,我们回显了所有类别,它们之间有spaceReference Here.
【解决方案2】:

我能够使用以下方法使其正常工作。

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

【讨论】:

    【解决方案3】:

    通过使用以下内容,我能够获得显示类别和标题的列表。

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

    我永远无法让以下代码在我的原始代码中工作它总是显示为“数组”或 Null(我猜我只是不知道写入它的正确方法)我能够如果我创建了一个帖子并且只想显示类别而没有其他内容,则让它显示类别。

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

    【讨论】:

      【解决方案4】:

      我使用了 Jaco 的答案,但是

          $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();
      

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签