在 AJAX 分页加载中,如何正确重建 WP_Query 并保留 SEO 的 rel="next"?
解读
国内多数企业把“无限滚动/AJAX 分页”当成提升“用户体验与转化率”的刚需,却常被百度、搜狗、360 的 Spider 直接忽略,导致收录断层与排名下滑。
面试官真正想确认的是:
- 你能否在不刷新页面的前提下,用 JS 拉取第 n 页内容;
- 同时让首屏 HTML 依旧输出带
rel="next"的标准分页链接,保证搜索引擎能顺链抓取; - 当 JS 不可用时,** gracefully fallback 到普通分页,避免白屏。
一句话:“人看 AJAX,蜘蛛看<link>”**。
知识点
- WP_Query 的 paged 与 offset 混用陷阱:AJAX 传参务必用
paged,禁止手动算 offset,否则破坏 SQL 的索引命中。 - pre_get_posts 与 is_main_query() 判断:防止后台/admin 也被 AJAX 钩子污染。
- rel="next"/"prev" 输出时机:仅在首屏且非 AJAX 时通过
get_next_posts_link()与adjacent_rel_links()写入<head>;AJAX 片段不再重复输出。 - REST API 路由自定义:推荐走
/wp-json/wp/v2/posts?per_page=6&page=2,自带X-WP-TotalPages响应头,省掉二次 count 查询。 - 缓存友好:在 Nginx fastcgi_cache 或 CDN 中,对
page=1缓存 1h,对page>1缓存 5min,降低回源。 - 百度主动推送:AJAX 加载的新页,仍需在后台用
wp_remote_post()把新 URL 推送到百度,避免蜘蛛漏爬。 - noscript 兜底:在列表容器后输出
<noscript><a href="?paged=2">第2页</a></noscript>,兼顾无障碍与 SEO。
答案
- 主题模板首页/分类页首屏正常输出
$paged = max( 1, get_query_var('paged') );
$query = new WP_Query( [
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
'no_found_rows' => false, // 需要总页数
] );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
get_template_part( 'template-parts/content' );
endwhile;
endif;
// 仅首屏输出 rel="next"
if ( $paged < $query->max_num_pages ) {
printf( '<link rel="next" href="%s">', esc_url( get_next_posts_page_link() ) );
}
wp_reset_postdata();
- 注册 REST 路由,供 AJAX 调用
add_action( 'rest_api_init', function () {
register_rest_route( 'theme/v1', '/ajax-list/(?P<page>\d+)', [
'methods' => 'GET',
'callback' => 'theme_ajax_list',
'permission_callback' => '__return_true',
] );
} );
function theme_ajax_list( WP_REST_Request $r ) {
$page = absint( $r['page'] );
$q = new WP_Query( [
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $page,
'no_found_rows' => false,
] );
$html = '';
while ( $q->have_posts() ) {
$q->the_post();
ob_start();
get_template_part( 'template-parts/content' );
$html .= ob_get_clean();
}
return [
'html' => $html,
'max_pages' => $q->max_num_pages,
'next_link' => $page < $q->max_num_pages ? get_next_posts_page_link( $page ) : '',
];
}
- JS 端(jQuery 示例)
let page = 1;
let canGet = true;
const $list = $('#post-list');
const ajaxUrl = wpApiSettings.root + 'theme/v1/ajax-list/';
function loadMore() {
if (!canGet) return;
canGet = false;
page++;
$.get(ajaxUrl + page).done(res=>{
$list.append(res.html);
canGet = page < res.max_pages;
// 更新浏览器历史,方便回退
history.replaceState(null, null, res.next_link);
});
}
// 滚动监听
$(window).on('scroll', function(){
if ($(window).scrollTop() + $(window).height() > $(document).height() - 300) {
loadMore();
}
});
- 后台推送新页到百度
add_action( 'wp_ajax_nopriv_theme_ajax_list', function(){
// 仅示例:当加载到第3页时推送
if( $_GET['page'] == 3 ){
$api = 'http://data.zz.baidu.com/urls?site=https://www.example.com&token=YOUR';
wp_remote_post( $api, [ 'body' => implode( "\n", array_map( 'get_permalink', $GLOBALS['wp_query']->posts ) ) ] );
}
} );
关键点:
- 首屏必带
rel="next",AJAX 片段不再输出; - REST 路由用
paged参数,绝不手工 offset; - 总页数通过
no_found_rows => false一次查完; - 浏览器历史用
replaceState保持 URL 同步,用户刷新仍可回到正确分页; - 若蜘蛛直接访问
?paged=n,依旧返回完整 HTML,URL 统一,权重不分散。
拓展思考
- Gutenberg + Interactivity API:WordPress 6.5 已内置
@wordpress/interactivity脚本,可直接把分页做成声明式区块,省去 jQuery,FCP 提升 20%。 - Edge Cache Key:在阿里云全站加速里,把
page参数加入缓存键,避免第2页被当成首页缓存。 - Big Data 场景:当文章 >10 万,MySQL 深分页导致 filesort;可改用ES 索引或wp-seed-search插件,把分页逻辑迁到 ElasticSearch,WP_Query 只回 ID 列表。
- 安全:AJAX 接口务必用
sanitize_text_field()过滤页码,并加nonce,防止恶意遍历触发 MySQL 全表扫描。 - 广告填充:国内站常需在列表第6、12 位插入百度联盟广告位,可在 REST 返回前,用
DomDocument解析$html,动态插入广告节点,再返回给前端,保证广告可见率与 SEO 无关代码分离。