如何将WordPress新闻网站转为Flutter应用并获取完整数据?
WordPress REST API 获取全量数据及扩展内容解决方案
一、解决全量文章数据获取问题
修正分页参数与后台设置
WP REST API 默认per_page上限受后台“阅读设置”控制:进入WP后台→设置→阅读,修改“博客页面最多显示”的数值(默认10)。之后使用正确的参数格式请求:https://example.com/wp-json/wp/v2/posts?per_page=100&page=1响应头里的
X-WP-Total(总文章数)和X-WP-TotalPages(总页数)可帮你判断需要循环请求多少页。突破
per_page上限限制
如果后台修改后仍无法设置更大的per_page值,在主题的functions.php中添加以下代码扩展API上限:add_filter( 'rest_post_collection_params', 'custom_rest_post_per_page', 10, 1 ); function custom_rest_post_per_page( $params ) { if ( isset( $params['per_page'] ) ) { $params['per_page']['maximum'] = 500; // 按需调整最大值 } return $params; }
二、获取评论、点赞、分享数及相关新闻
评论数据
两种方式获取:- 单独请求评论端点:
https://example.com/wp-json/wp/v2/comments?post=<文章ID> - 嵌入到文章请求中,添加
_embed参数:
响应中每个文章的https://example.com/wp-json/wp/v2/posts?_embed&per_page=100_embedded['replies']字段会包含对应评论。
- 单独请求评论端点:
点赞/分享数
这类数据通常来自自定义字段或第三方插件,可通过自定义REST字段暴露:
在functions.php中添加代码(替换实际的meta键):add_action( 'rest_api_init', 'add_post_like_share_fields' ); function add_post_like_share_fields() { register_rest_field( 'post', 'like_count', array( 'get_callback' => fn( $post ) => get_post_meta( $post['id'], 'like_count', true ), 'schema' => array( 'description' => '文章点赞数', 'type' => 'integer' ), ) ); register_rest_field( 'post', 'share_count', array( 'get_callback' => fn( $post ) => get_post_meta( $post['id'], 'share_count', true ), 'schema' => array( 'description' => '文章分享数', 'type' => 'integer' ), ) ); }之后请求文章时就能直接拿到
like_count和share_count字段。相关新闻
基于分类/标签关联实现,可在functions.php中添加自定义字段返回相关文章:add_action( 'rest_api_init', 'add_related_posts_field' ); function add_related_posts_field() { register_rest_field( 'post', 'related_posts', array( 'get_callback' => function( $post ) { $related_posts = get_posts( array( 'category__in' => wp_get_post_categories( $post['id'] ), 'numberposts' => 5, // 显示数量 'post__not_in' => array( $post['id'] ) ) ); return rest_prepare_posts( $related_posts ); }, 'schema' => array( 'description' => '相关新闻', 'type' => 'array' ), ) ); }
三、基于你的技术栈的优化建议
- Node.js中间层
直接在Flutter中处理分页请求会增加客户端复杂度,用Node.js做中间层:- 用Axios等工具循环请求所有分页的文章数据,合并为全量数据集
- 统一处理评论、点赞、相关新闻等扩展字段的拼接
- 给Flutter提供一个简化的接口,直接返回整理好的全量数据,还可加入缓存逻辑提升性能
四、关于API的说明
不需要额外索要“主API”,WP REST API就是官方提供的标准接口,通过上述配置和扩展即可满足你的所有需求。
内容的提问来源于stack exchange,提问作者Archak
相关产品推荐
相关产品推荐

