在 WordPress 中调用、跳转、展示指定分类的文章列表页,我把最常用、最实用的方法一次性给全,直接复制就能用。
一、基础概念
分类页:category.php(主题模板文件)
分类标识:分类 ID / 分类别名 (slug)
分类页链接格式:
默认:yoursite.com/category/分类别名/
自定义:yoursite.com/分类别名/
二、最常用 4 种调用方法
1. 跳转到指定分类页(链接 / 按钮)
php
方法 A:用 分类别名(推荐)
<a href="<?php echo get_category_link('news'); ?>">新闻分类</a>
方法 B:用 分类 ID
<a href="<?php echo get_category_link(5); ?>">ID=5 的分类</a>
2. 在任意页面调用「指定分类的文章列表」
展示某个分类下的文章,不跳转,直接输出列表:
php
<?php
// 调用 分类ID=5 的最新6篇文章
$args = array(
'cat' => 5, // 分类ID
'posts_per_page' => 6 // 显示数量
);
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) :
while( $my_query->have_posts() ) : $my_query->the_post();
?>
<!-- 文章标题+链接 -->
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<!-- 发布时间 -->
<p><?php the_time('Y-m-d'); ?></p>
<!-- 摘要 -->
<p><?php the_excerpt(); ?></p>
<?php
endwhile;
wp_reset_postdata(); // 重置查询
endif;
?>
3. 调用「多个分类」或「排除某个分类」
php
// 调用 分类3 + 分类5
'cat' => '3,5'
// 排除 分类ID=2
'cat' => '-2'
4. 调用「所有分类列表」(导航 / 侧边栏)
php
<?php
wp_list_categories( array(
'title_li' => '', // 去掉默认标题
'orderby' => 'name', // 按名称排序
'show_count' => 1 // 显示文章数量
) );
?>
三、主题模板:制作独立分类页
不同分类用不同分类样式:
复制主题里的 category.php
重命名为:
php
category-5.php(对应 ID=5)//分类ID为5的分类会使用此模板
category-news.php(对应别名 news)//分类名为news的分类会使用此模板
WordPress 会自动识别并加载
还有一种方法通过functions绑定
php
// 指定 某个分类 使用 category-card.php 模板
add_filter( 'template_include', 'custom_category_template' );
function custom_category_template( $template ) {
// 👇 在这里修改为 你的分类ID 或 分类别名,二选一
$target_category_id = 8; // 要使用卡片模板的分类ID
//$target_category_slug = 'news'; // 或者用别名
if ( is_category( $target_category_id ) && file_exists( get_template_directory() . '/category-card.php' ) ) {
$template = get_template_directory() . '/category-card.php';//使用此分类归档模板
}
return $template;
}