Wordpress相关帖子通过类别外循环

时间:2012-03-15 05:17:21

标签: wordpress foreach

我在网上发现了这段代码并完成了我需要它做的事情,它通过单个模板中的循环外的类别给我一个相关帖子的列表。

<?php
    $postid = $post->ID;
    foreach((get_the_category()) as $category) {
        echo "<h3>Related Posts in ".$category->cat_name." </h3>";
        $postlist = get_posts('category='.$category->cat_name);
            foreach ($postlist as $post) :
                $catpostid = $post->ID;
                    if (in_category($category->cat_name) && ($catpostid != $postid)) { ?>
                        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
                <?php }
            endforeach;
      }
?>

任何人都可以帮我添加一个帖子计数参数吗?我一直试图修改这个几个小时,我一直打破它。我只需要能够控制出现的帖子数量。对不起,但在使用PHP编写任何代码时,我是一个完整的小组。

感谢。

1 个答案:

答案 0 :(得分:0)

你可以将numberposts参数传递给get_posts()以及你的类别......我已经在$ args =行列出了几个想法,只允许10个帖子,按标题升序排序,来自你的分类名称。当然完全未经测试,但随意玩吧!

<?php
  $postid = $post->ID;
  foreach((get_the_category()) as $category) {
   echo "<h3>Related Posts in ".$category->cat_name." </h3>";
   $args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title', 'category' => $category->cat_name );
   $postlist = get_posts( $args );
   foreach ($postlist as $post) :
   $catpostid = $post->ID;
   if (in_category($category->cat_name) && ($catpostid != $postid)) { ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
   <?php }
   endforeach;
  } ?>
相关问题