WordPress博客页面分页功能失效问题求助
WordPress短代码分页修复方案
先给你修正后的可用代码,再拆解问题原因:
function show_posts_shortcode($atts){ ob_start(); extract(shortcode_atts(array( 'posts' => 5, // 默认每页5篇,替换原-1(显示全部)的设置 'cat' => '', 'show_cat' => false, 'orderby' => 'date', // 补全排序依据参数 'order' => 'DESC', 'post_id' => '' ), $atts)); // 兼容博客页面(paged)和静态页面(page)的分页参数 $paged = (get_query_var('paged')) ? get_query_var('paged') : (get_query_var('page') ? get_query_var('page') : 1); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category_name' => $cat, // 启用短代码的cat参数 'posts_per_page' => $posts, 'orderby' => $orderby, 'order' => $order, 'paged' => $paged ); // 移除无效的单篇文章逻辑,避免干扰多文章查询 $arr_posts = new WP_Query( $args ); if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?> > <div class="image_cusm"> <?php if ( has_post_thumbnail() ) : the_post_thumbnail(); endif; ?> </div> <header class="entry-header"> <h1 class="entry-title" ><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> </header> <div class="entry-content"> <span class='cat_cus'><?php the_category(', '); ?> </span> <p class="author_clas"><i class="fas fa-user-edit"></i> <?php the_author(); ?></p> <p class="meta_date"> <?php the_time( 'd M' ); ?> </p> <?php the_excerpt(); ?> <a href="<?php the_permalink(); ?>">Read More</a> </div> </article> <?php endwhile; // 修正分页变量,使用正确的查询对象 $total_pages = $arr_posts->max_num_pages; if ($total_pages > 1){ $current_page = max(1, $paged); echo paginate_links(array( // 用WordPress官方推荐写法适配分页链接 'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))), 'format' => '?paged=%#%', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => __('« prev'), 'next_text' => __('next »'), )); } // 重置查询,避免影响页面其他内容 wp_reset_postdata(); endif; return ob_get_clean(); } add_shortcode("show_posts","show_posts_shortcode");
核心问题与修改说明:
- 分页变量错误:原代码用了未定义的
$data->max_num_pages,实际应该用查询对象$arr_posts->max_num_pages才能正确获取总页数 - 默认显示逻辑错误:原
posts默认值为-1(显示所有文章),分页自然不会触发,改成5后默认每页显示5篇,也可通过短代码参数自定义,比如[show_posts posts="8"] - 无效代码干扰:移除了
if(empty($post_id))的逻辑,这段代码会错误加载单篇文章,打乱多文章的循环查询 - 参数未生效:把
category_name设为$cat,让短代码的分类参数生效;修正排序参数,原代码把排序方向赋值给了排序依据,现在拆分出orderby参数保证逻辑正确 - 分页链接适配:用WordPress官方推荐的
base写法,兼容博客页面和静态页面的分页参数,避免跳转错误 - 查询重置:添加
wp_reset_postdata(),防止自定义查询影响页面其他内容的正常渲染
内容的提问来源于stack exchange,提问作者Max_07
相关产品推荐
相关产品推荐

