【问题标题】:Wordpress Related Posts via Category Outside Loop通过类别外循环的 WordPress 相关帖子
【发布时间】:2012-03-15 05:17:20
【问题描述】:

我在网上找到了这个 sn-p 代码,并做了我需要它做的事情,即通过单个模板中的循环外的类别给我一个相关帖子的列表。

<?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 中编写任何代码时,我是一个完整的小块。

谢谢。

【问题讨论】:

    标签: wordpress foreach


    【解决方案1】:

    您可以将 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;
      } ?>
    

    【讨论】:

    • 有关您可以传递给 get_posts 的参数的完整列表,还请查看 Wordpress 文档:codex.wordpress.org/Template_Tags/get_posts
    • 尝试了您提供的代码,它没有中断或给出任何错误。但奇怪的是,当我将数字帖子从 10 个降至 4 个时,它只显示 1 个相关帖子。此测试类别中有 3 个帖子,因此应该显示两个相关帖子。正如我在上面所说的 4 个帖子和下面只显示 1 个相关帖子,但是 5-10 并且我假设 10 以上的任何数字显示 2 个帖子。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多