首页 问答 正文

如何在WordPress中显示特定类别的文章?

注册会员 / 悠然自学 / 2023-06-12/ 浏览 140 次

要在WordPress中显示特定类别的文章,可以使用查询参数cat来指定需要显示的类别ID。以下是在WordPress中显示特定类别文章的示例代码:

<?php
$args = array(
  'category__in' => array(1, 2, 3), // 替换为你要显示的类别ID
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => 5 // 替换为你要显示的文章数量
);

$query = new WP_Query($args);

if ($query->have_posts()) {
  while ($query->have_posts()) {
    $query->the_post();
    // 在这里可以显示文章的标题、内容等
    the_title();
    the_content();
    // ...
  }
} else {
  // 如果没有匹配的文章,则输出提示信息
  echo '没有找到相关文章。';
}

wp_reset_postdata();
?> 

上述示例代码会显示ID为1、2和3的类别中的最近的5篇文章。你可以根据需要更改类别ID和文章数量,以适应你的具体需求。

大家谈论
    我的见解