如何通过Gutenberg API获取单篇文章的渲染后模板HTML?
获取自定义文章类型单页的完整渲染HTML(基于Gutenberg/REST API)
默认的WP REST API wp/v2/posts/{id} 接口仅返回文章内容区块的渲染结果,不会包含主题模板的完整结构。要获取包含模板的完整单页HTML,有两种可靠方案:
方案1:自定义REST API端点(推荐)
直接注册一个自定义端点,复用WP原生的模板渲染逻辑,返回完整页面HTML,性能和渲染一致性最佳。
在主题的functions.php或自定义插件中添加以下代码:
add_action('rest_api_init', function () { register_rest_route( 'custom/v1', '/post-render/(?P<id>\d+)', array( 'methods' => 'GET', 'callback' => 'get_full_post_render_html', // 按需调整权限,比如仅允许登录用户访问私有内容 'permission_callback' => function () { return current_user_can('read'); }, ) ); }); function get_full_post_render_html($request) { $post_id = $request['id']; $post = get_post($post_id); // 验证文章存在且属于目标自定义文章类型 if (!$post || $post->post_type !== 'your_cpt_slug') { // 替换为你的CPT别名 return new WP_Error('invalid_post', '文章不存在或类型不匹配', array('status' => 404)); } // 输出缓冲捕获模板渲染内容 ob_start(); setup_postdata($post); // WP会自动匹配对应模板(如single-your_cpt_slug.php或区块模板) get_template_part('single', $post->post_type); wp_reset_postdata(); $full_html = ob_get_clean(); return array( 'post_id' => $post_id, 'full_html' => $full_html ); }
使用时直接请求https://example.com/wp-json/custom/v1/post-render/{id}即可拿到完整渲染的单页HTML。
方案2:通过前端URL请求HTML
如果不想自定义端点,可以直接请求文章的前端永久链接,获取页面HTML内容。这种方式简单但性能略差(多一次HTTP请求):
function get_post_full_html_via_permalink($post_id) { $post = get_post($post_id); if (!$post) return new WP_Error('invalid_post', '文章不存在', array('status' => 404)); $permalink = get_permalink($post_id); $response = wp_remote_get($permalink); if (is_wp_error($response)) { return $response; } return wp_remote_retrieve_body($response); }
注意事项
- 若使用区块主题,
get_template_part会自动加载对应的区块模板(如single.html或自定义区块模板),渲染结果和前端完全一致。 - 自定义端点可扩展参数,比如添加
strip_layout参数控制是否移除header/footer,只需在回调中判断参数并调整渲染的模板片段。 - 务必根据内容敏感度设置合适的权限验证,防止未授权访问。
内容的提问来源于stack exchange,提问作者yfain
相关产品推荐
相关产品推荐

