使用WordPress Rewrite API实现AJAX请求时遇JSON响应异常求助
问题分析与解决
问题根源
- 核心文件修改风险:直接修改
wp-includes/functions.php是错误操作,这是WordPress核心文件,后续系统更新会覆盖你的自定义代码。所有自定义逻辑都应放在当前激活主题的functions.php或自定义插件中。 - 缺少参数判断逻辑:你的
template_redirect回调函数没有检查是否存在filter_id参数,导致每次访问站点(包括首页)都会执行wp_send_json_success,直接返回JSON响应,中断了正常页面加载流程。
修正方案
1. 迁移代码到正确位置
把代码从wp-includes/functions.php移到当前激活主题的functions.php文件中(路径一般为wp-content/themes/你的主题名/functions.php),或者创建一个简单的自定义插件。
2. 修改回调逻辑,添加参数判断
更新template_redirect的回调函数,仅在检测到filter_id参数时才处理AJAX逻辑,否则让WordPress正常加载页面:
add_action( 'init', function () { add_rewrite_tag( '%filter_id%', '([0-9]+)' ); add_rewrite_rule( 'filter/([0-9]+)/?', 'index.php?filter_id=$matches[1]', 'top' ); }); add_action( 'template_redirect', function () { global $wp_query; // 仅当存在filter_id参数时才执行后续逻辑 if ( ! isset( $wp_query->query_vars['filter_id'] ) ) { return; } $filter_id = $wp_query->query_vars['filter_id']; // 替换为你的实际查询逻辑,以下以根据分类ID获取文章为例 $filtered_posts = get_posts( array( 'post_type' => 'post', 'cat' => $filter_id, 'posts_per_page' => -1, ) ); if ( ! empty( $filtered_posts ) ) { $response = array(); foreach ( $filtered_posts as $post ) { $response[] = array( 'id' => $post->ID, 'title' => get_the_title( $post->ID ), 'permalink' => get_permalink( $post->ID ) ); } wp_send_json_success( $response ); } else { wp_send_json_error( array( 'message' => '未找到匹配内容' ) ); } });
3. 刷新固定链接规则
添加完重写规则后,进入WordPress后台的设置 → 固定链接页面,无需修改任何选项,直接点击「保存更改」,WordPress会刷新重写规则,让你的自定义filter/[ID]路由生效。
运行机制说明
WordPress Rewrite API的作用是将自定义URL(如firstwp.test/filter/1)映射到index.php并传递指定参数(这里是filter_id=1)。template_redirect钩子会在WordPress准备加载页面模板前触发,如果你在这个钩子中调用wp_send_json_success或wp_send_json_error,WordPress会直接返回JSON响应并终止后续的页面加载流程——这也是之前首页返回JSON的原因:因为没有判断参数,每次访问都会执行这个终止逻辑。
内容的提问来源于stack exchange,提问作者DimAnd
相关产品推荐
相关产品推荐

