【问题标题】:wordpress displays all posts instead of categorisedwordpress 显示所有帖子而不是分类
【发布时间】:2025-12-08 09:50:02
【问题描述】:

我正在尝试让不同类别的帖子显示在不同的页面上,以便我可以将它们用于“服务”和“案例研究”页面。

我设置了两个页面,它们显示每个帖子的链接,但是显示所有帖子,而不仅仅是特定类别。

我在每个页面上的代码都是相同的,除了帖子类别 ID。

如何在单独的页面上显示单独的类别?

服务页面:

              <?php // PAGE LINK/TITLE


if (is_page()) {
  $cat=get_cat_ID($post->post_title); //use page title to get a category ID
  $posts = get_posts ("cat=$cat&showposts=4");
  if ($posts) {
    foreach ($posts as $post):
      setup_postdata($post); 

                  if ( has_post_thumbnail() ) { // PULLS IN IMAGE check if the post has a Post Thumbnail assigned to it.
    the_post_thumbnail();
} 


    ?>




      <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

      <?php //PULLS IN EXCERPT
$my_excerpt = get_the_excerpt();
if ( '' != $my_excerpt ) {
    // Some string manipulation performed
}
echo $my_excerpt; // Outputs the processed value to the page




?>
          <?php endforeach;
  }
}
?> 

案例研究页面:

        <?php // PAGE LINK/TITLE


if (is_page()) {
  $cat=get_cat_ID($post->post_title); //use page title to get a category ID
  $posts = get_posts ("cat=$cat&showposts=5");
  if ($posts) {
    foreach ($posts as $post):
      setup_postdata($post); 

                  if ( has_post_thumbnail() ) { // PULLS IN IMAGE check if the post has a Post Thumbnail assigned to it.
    the_post_thumbnail();
} 


    ?>




      <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

      <?php //PULLS IN EXCERPT
$my_excerpt = get_the_excerpt();
if ( '' != $my_excerpt ) {
    // Some string manipulation performed
}
echo $my_excerpt; // Outputs the processed value to the page




?>
          <?php endforeach;
  }
}
?> 

【问题讨论】:

  • 停止滥用 $posts 全局并将任何垃圾分配给全局。另外,在更改后重置$post 全局
  • 我不知道 PHP 或 wordpress,所以我该如何更改上面的内容以显示特定的分​​类帖子?

标签: php wordpress post content-management-system blogs


【解决方案1】:

回答

没有设置具体的类别,只有要显示的帖子数量,在本例中为 10。

 <?php // PAGE LINK/TITLE


if (is_page()) {
  $cat=get_cat_ID($post->post_title); //use page title to get a category ID

  $posts = get_posts ("category_name=service&posts_per_page=10"); //CHANGE CODE AND ADD THIS LINE***************************

  if ($posts) {
    foreach ($posts as $post):
      setup_postdata($post); 

                  if ( has_post_thumbnail() ) { // PULLS IN IMAGE check if the post has a Post Thumbnail assigned to it.
    the_post_thumbnail();
} 


    ?>

这设置了具体的类别和帖子的数量(使用类别slug将其拉入)

category_name=service&posts_per_page=10

【讨论】: