如何在Rank Math插件中获取JSON格式的元头部数据
如何从Rank Math获取JSON格式的元头部数据
Rank Math默认输出HTML格式的meta标签,要转换成你需要的JSON结构,可通过以下两种方式实现:
方式一:在页面头部输出JSON格式元数据
添加以下PHP代码到你的WordPress主题(推荐子主题)的functions.php文件,或自定义插件中:
// 移除Rank Math默认的HTML meta输出 remove_action( 'wp_head', 'rank_math/frontend/head', 1 ); // 自定义输出JSON格式的元数据 add_action( 'wp_head', 'custom_rank_math_json_meta', 1 ); function custom_rank_math_json_meta() { // 获取当前文章/页面的Rank Math元数据 $post_meta = RankMath\Helper::get_meta( get_the_ID() ); // 构建目标JSON结构 $json_output = [ 'head' => [ 'title' => $post_meta['title'] ?? get_the_title(), 'description' => $post_meta['description'] ?? get_bloginfo( 'description' ) ] ]; // 输出JSON(用script标签包裹,避免HTML解析冲突) echo '<script type="application/json">' . json_encode( $json_output ) . '</script>'; }
这段代码会替换Rank Math默认的HTML meta标签,在页面头部输出你需要的JSON结构,前端可通过读取该script标签的内容获取数据。
方式二:通过REST API接口获取JSON数据
如果需要通过API请求单独获取元数据,可添加以下代码创建自定义REST路由:
add_action( 'rest_api_init', function() { // 注册自定义API路由,支持通过文章ID获取元数据 register_rest_route( 'custom/v1', '/post-meta/(?P<id>\d+)', [ 'methods' => 'GET', 'callback' => 'custom_get_rank_math_meta' ] ); } ); function custom_get_rank_math_meta( $request ) { $post_id = $request['id']; $post_meta = RankMath\Helper::get_meta( $post_id ); // 组装返回的JSON结构 $response_data = [ 'head' => [ 'title' => $post_meta['title'] ?? get_the_title( $post_id ), 'description' => $post_meta['description'] ?? get_post_meta( $post_id, '_rank_math_description', true ) ] ]; return new WP_REST_Response( $response_data, 200 ); }
添加完成后,访问你的域名/wp-json/custom/v1/post-meta/文章ID即可获取对应文章的JSON格式元数据。
注意事项
- 修改主题文件前请做好备份,优先使用子主题或自定义插件添加代码,避免主题更新导致代码丢失;
- 确保Rank Math插件已激活,且
RankMath\Helper类可正常调用; - 若某些文章未设置Rank Math标题/描述,代码会自动 fallback 到文章默认标题或站点描述。
内容的提问来源于stack exchange,提问作者Alireza Bagheri
相关产品推荐
相关产品推荐

