如何在WordPress单页实现不同自定义文章类型的多分页
WordPress单页面多CPT友好分页实现方案
1. 注册自定义查询变量
在主题的functions.php中添加代码,让WordPress识别我们需要的分页相关变量:
function register_cpt_pagination_vars($vars) { $vars[] = 'cpt_type'; $vars[] = 'cpt_page'; return $vars; } add_filter('query_vars', 'register_cpt_pagination_vars');
2. 添加重写规则
同样在functions.php中配置URL重写规则,把友好格式的URL映射到WordPress可解析的参数。记得把RELEASE_PAGE_ID替换成你实际的release页面ID:
function add_cpt_pagination_rewrite_rules() { // 匹配带页码的路径,比如/release/news/2/ add_rewrite_rule( '^release/(news|resource)/([0-9]+)/?$', 'index.php?page_id=RELEASE_PAGE_ID&cpt_type=$matches[1]&cpt_page=$matches[2]', 'top' ); // 匹配不带页码的默认路径,比如/release/news/ add_rewrite_rule( '^release/(news|resource)/?$', 'index.php?page_id=RELEASE_PAGE_ID&cpt_type=$matches[1]&cpt_page=1', 'top' ); } add_action('init', 'add_cpt_pagination_rewrite_rules');
3. 在Release页面模板中处理查询
打开你的release页面模板(比如page-release.php),根据获取到的变量查询对应CPT内容并渲染:
<?php // 获取自定义查询变量,默认显示news类型 $cpt_type = get_query_var('cpt_type', 'news'); $current_page = get_query_var('cpt_page', 1); $posts_per_page = 10; // 按需修改每页显示数量 // 限制允许的CPT类型,避免非法请求 $allowed_cpts = ['news', 'resource']; if (!in_array($cpt_type, $allowed_cpts)) { $cpt_type = 'news'; } // 构建CPT查询参数 $args = [ 'post_type' => $cpt_type, 'posts_per_page' => $posts_per_page, 'paged' => $current_page, 'post_status' => 'publish' ]; $cpt_query = new WP_Query($args); ?> <!-- 渲染CPT内容列表 --> <?php if ($cpt_query->have_posts()) : ?> <div class="cpt-list"> <?php while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?> <article class="cpt-item"> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> </article> <?php endwhile; ?> </div> <!-- 渲染友好分页链接 --> <div class="pagination"> <?php $total_pages = $cpt_query->max_num_pages; if ($total_pages > 1) { $current_page = max(1, $current_page); $base_url = home_url("/release/{$cpt_type}/"); // 上一页链接 if ($current_page > 1) { $prev_url = $current_page - 1 == 1 ? $base_url : "{$base_url}" . ($current_page - 1) . "/"; echo "<a href='{$prev_url}' class='prev'>上一页</a>"; } // 页码列表 for ($i = 1; $i <= $total_pages; $i++) { $page_url = $i == 1 ? $base_url : "{$base_url}{$i}/"; $active = $i == $current_page ? 'active' : ''; echo "<a href='{$page_url}' class='page-num {$active}'>{$i}</a>"; } // 下一页链接 if ($current_page < $total_pages) { $next_url = "{$base_url}" . ($current_page + 1) . "/"; echo "<a href='{$next_url}' class='next'>下一页</a>"; } } ?> </div> <?php else : ?> <p>暂无相关内容</p> <?php endif; ?> <?php wp_reset_postdata(); ?>
4. 刷新重写规则
添加完规则后,进入WordPress后台「设置」→「固定链接」,直接点击「保存更改」按钮,让新的重写规则生效。
注意事项
- 确保你的自定义文章类型(news、resource)已经正确注册,
has_archive属性设为false也不影响此方案。 - 后续新增CPT时,只需修改
allowed_cpts数组,并在重写规则的正则中添加新的CPT标识(比如(news|resource|new_cpt))。 - 分页样式可根据主题需求自行调整CSS。
内容的提问来源于stack exchange,提问作者B104 Sanket naikwadi
相关产品推荐
相关产品推荐

