WordPress自定义分类法分页失效问题求助
自定义分类法分页404问题排查与解决
我创建了名为species_guide的自定义文章类型(CPT)和名为species的自定义分类法,但分页功能异常:第一页正常显示,点击/page/2/时出现404错误。尝试过相关分页方案但无效。
现有代码片段
taxonomy-species.php文件代码
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $term_slug = get_query_var('species'); $args = array( 'post_type' => 'species_guide', 'tax_query' => array( array( 'taxonomy' => 'species',//custom taxonomy name 'field' => 'slug', 'terms' => $term_slug ) ), 'posts_per_page' => 10, 'paged' => $paged ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); get_template_part( 'templates/post-archive' ); endwhile; ?> <div class="pagination"> <?php $big = 999999999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $loop->max_num_pages, 'prev_text' => '«', 'next_text' => '»' ) ); wp_reset_postdata(); ?>
functions.php文件代码
function custom_tax_query_change( $query ) { if ( ! is_admin() && $query->is_tax( 'species' ) ) { $query->set( 'posts_per_page', 10 ); } } add_action( 'pre_get_posts', 'custom_tax_query_change' );
我不确定是否需要在is_tax()函数中使用不同的species别名,也不清楚问题出在哪里。
问题分析与解决建议
核心问题原因
- 同时使用
pre_get_posts修改主查询和自定义WP_Query,WordPress重写规则会因主查询与自定义查询的分页参数不匹配失效,导致第二页无对应规则。 paginate_links的format参数设置为?paged=%#%,但分类法归档默认分页URL结构是/page/2/,GET参数格式与重写规则不兼容。
修复步骤
移除自定义WP_Query,直接使用主查询
既然已在pre_get_posts中设置分类法参数,可直接用主查询渲染内容,避免参数冲突。修改taxonomy-species.php代码:<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'templates/post-archive' ); endwhile; ?> <div class="pagination"> <?php $big = 999999999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => 'page/%#%/', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_text' => '«', 'next_text' => '»' ) ); ?> </div> <?php wp_reset_postdata(); endif; ?>完善pre_get_posts函数,补充post_type参数
原函数仅设置了posts_per_page,需强制指定post_type确保主查询只获取目标文章类型,避免分页计数错误。修改functions.php代码:function custom_tax_query_change( $query ) { if ( ! is_admin() && $query->is_tax( 'species' ) && $query->is_main_query() ) { $query->set( 'post_type', 'species_guide' ); $query->set( 'posts_per_page', 10 ); } } add_action( 'pre_get_posts', 'custom_tax_query_change' );刷新固定链接规则
完成代码修改后,进入WordPress后台 → 设置 → 固定链接,直接点击「保存更改」按钮,强制刷新重写规则,确保分页URL规则生效。
额外说明
is_tax('species')用法正确,此处使用的是分类法slug,无需修改别名。- 避免同一归档页面同时使用主查询和自定义查询,会引发分页规则冲突、计数错误等问题。
内容的提问来源于stack exchange,提问作者Geri Atric
相关产品推荐
相关产品推荐

