WordPress+Ajax+Timber同分类文章加载更多功能失效求助
核心故障定位
加载更多失效的根本原因,是AJAX请求场景下后端无法获取正确的分类ID,导致分类筛选查询条件为空,无法返回对应文章。
- 你在
get_news函数中用global $post获取分类的写法不成立:WordPress处理admin-ajax.php请求时是独立的生命周期,不会自动加载当前浏览页面对应的全局文章对象,此时$post为空,get_the_category($post->ID)无法拿到有效分类ID,传入category__in的值是空数组,查询结果自然为空。 - 首次页面加载时获取到的分类ID没有通过前端传递给AJAX接口,后端就算有逻辑想读取分类也无数据源可用。
分步修正方案
1. 首次页面加载时将分类ID传递到前端模板
在archive.php中,把已经获取到的分类ID传入上下文:
// 你原有获取分类的逻辑保持不变 $category = get_the_category($post->ID); $category_id = $category[0]->cat_ID; // 新增:把分类ID传给模板 $context['current_category_id'] = $category_id; // 原有文章查询逻辑保持不变 $context['posts'] = Timber::get_posts(array( 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => array($category_id), 'posts_per_page' => 10, 'paged' => 1, 'has_password' => FALSE ));
在archive.twig中,把分类ID存在加载按钮的自定义属性上,方便JS读取:
{# 修改原有加载按钮代码 #} {% if posts|length >= 10 %} <section class="cta"> <a href="#" id="load-more-news" data-category-id="{{ current_category_id }}"> <p class="cta__text">加载更多文章</p> </a> </section> {% endif %}
2. 修改前端AJAX请求,传递分类ID
在script.js的AJAX配置中,新增分类ID的传参:
// 原有点击逻辑保持不变,仅修改data参数 $.ajax({ type: 'POST', url: '/wp-admin/admin-ajax.php', dataType: 'html', data: { 'action' : 'get_news', 'get_page' : page, 'category_id' : $('#load-more-news').data('category-id') // 新增传参 }, // 原有success、error回调保持不变 });
3. 修正后端AJAX回调的分类获取逻辑
删掉原有依赖全局$post取分类的代码,直接读取前端传递的分类ID,增加参数校验:
add_action( 'wp_ajax_nopriv_get_news', 'get_news' ); add_action( 'wp_ajax_get_news', 'get_news' ); function get_news() { $context = Timber::get_context(); // 接收参数并做类型校验,避免非法值 $context['get_page'] = isset($_POST['get_page']) ? max(1, intval($_POST['get_page'])) : 1; $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0; // 分类ID不合法时直接返回空内容 if ($category_id <= 0) { Timber::render( 'bloc_news.twig', $context ); die(); } // 原有文章查询逻辑保持不变 $context['posts'] = Timber::get_posts(array( 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => array($category_id), 'posts_per_page' => 10, 'paged' => $context['get_page'], 'has_password' => FALSE )); // 原有文章总数统计逻辑保持不变 $count = count(Timber::get_posts(array( 'post_type' => 'post', 'posts_per_page' => -1, 'post_status' => 'publish', 'category__in' => array($category_id) ))); // 原有结束状态判断逻辑保持不变 if($count <= $context['get_page'] * 10) $context['ended'] = 'ended'; Timber::render( 'bloc_news.twig', $context ); die(); }
常见踩坑提醒
- 处理AJAX请求时,不要依赖前台页面初始化的全局对象(比如
$post、当前$wp_query),admin-ajax是独立的请求流程,这些全局对象的状态和前台浏览的页面完全不连通。 - 所有前端传递到后端的数值参数,都要做整数类型转换,避免SQL注入风险。
内容的提问来源于stack exchange,提问作者Jandon
相关产品推荐
相关产品推荐

