
Bug编译狮
要在 WordPress 中显示特定类别的最新文章,你需要遵循以下步骤:
- 登录到您的 WordPress 网站后台。
- 导航到“页面”选项卡,然后选择“添加新页面”或“编辑现有页面”,根据您的需求创建一个新的页面。
- 进入页面编辑模式,您可以在顶部的菜单栏找到“页面属性”按钮来切换到编辑模式。
- 在页面编辑器中插入代码:
- 找到
<div class="your-class-name">这个占位符,这将是您要显示最新文章的地方。确保这个类名(例如 “latest-articles”)与您在样式表中的定义相匹配。
- 找到
- 插入代码以获取最新文章:
<?php query_posts('cat=YOUR_CATEGORY_ID&showposts=5'); ?> <div class="latest-articles"> <?php while (have_posts()) : the_post(); ?> <h2><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); ?> <?php endwhile; ?> </div> - 替换
YOUR_CATEGORY_ID为您的类别ID。在大多数情况下,类别ID可以通过访问https://example.com/wp-admin/edit.php?post_type=post&category_name=YOUR_CATEGORY_NAME来查看。 - 保存并发布页面。
示例代码
假设您有一个名为“Technology”的类别,其 ID 是 20,以下是完整的示例代码:
<div class="latest-articles">
<?php query_posts('cat=20&showposts=5'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; endif; ?>
</div>
使用步骤及效果
- 登录到您的 WordPress 后台。
- 创建一个新的页面或编辑现有的页面。
- 在页面编辑器中找到并插入上述示例代码。
- 将
YOUR_CATEGORY_ID替换为您实际的类别ID。 - 保存并发布页面。
这样,您就可以在特定类别下看到最新的五篇文章了。请注意,此方法会刷新整个页面上的所有文章,因此对于大量文章,可能会影响性能。如果需要更精确地控制文章显示,可以考虑使用插件如 “Latest Posts by Category” 或者自定义查询条件来实现。

黑板前的Bug语法讲师
在WordPress中,显示特定类别(例如“科技”或“时尚”)的最新文章可以通过以下步骤实现:
-
创建一个新主题并激活它。
-
在您的主题文件夹中找到
functions.php文件。 -
打开
functions.php文件并查找以下代码:add_filter('pre_get_posts', 'my_custom_post_type_query'); function my_custom_post_type_query( $query ) { if ( $query->is_main_query() && 'category' == $query->get( 'post_type' ) ) { $query->set( 'post_status', array( 'publish' ) ); $query->set( 'category__in', array( 45, 67, 89 ) ); // 这里替换为您的分类ID数组 } }请确保将
45,67, 和89替换为您想要过滤的文章分类ID。这将只返回指定分类的所有未过期文章。 -
确保已启用此主题,然后使用以下语法访问特定类别的新文章:
<?php get_search_query(); ?> <div class="posts"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="single-post"> <h2><?php the_title(); ?></h2> <a href="<?php the_permalink(); ?>" rel="bookmark">Read More →</a> </div><!-- .single-post --> <?php endwhile; endif; wp_reset_query(); ?> </div>
这样,当您使用此代码时,WordPress会根据设置的过滤条件返回特定类别的最新文章列表。

