WordPress模板页面API返回content.rendered为空如何解决?
WordPress REST API 获取模板构建页面内容为空的原因及解决方法
原因分析
- 你通过模板代码构建的页面,主体内容是硬编码在主题模板文件(比如
page-mySlug.php)里的,并没有存储在WordPress数据库的页面post_content字段中。 - WordPress REST API默认返回的
content.rendered字段,是对数据库中post_content的渲染结果,因为这个字段为空,所以返回值自然是空的。只有标题来自区块,说明标题存在post_title字段,因此API能正常返回标题内容。
实现方法
方法1:扩展REST API响应,添加模板渲染内容
在主题的functions.php中添加代码,注册一个自定义字段,让API返回模板渲染后的完整页面内容:
add_action('rest_api_init', function() { register_rest_field('page', 'template_rendered_content', array( 'get_callback' => function($post) { ob_start(); // 加载对应页面的模板文件,这里假设模板是page-mySlug.php get_template_part('page', $post->post_name); $content = ob_get_clean(); return $content; }, 'schema' => array( 'description' => '模板渲染的完整页面内容', 'type' => 'string' ) )); });
修改后,再次请求原API地址,响应中会新增template_rendered_content字段,直接用这个字段的值通过dangerouslySetInnerHTML渲染即可。
方法2:将模板内容转为短代码/自定义区块
把模板中的硬编码内容封装成短代码,然后在页面编辑器中插入该短代码,这样post_content就有了内容,API返回的content.rendered会自动渲染短代码内容:
// 在functions.php中注册短代码 add_shortcode('custom_page_content', function() { ob_start(); // 这里放入原来模板文件中的HTML内容 ?> <div class="custom-page-wrapper"> <!-- 模板中的原有内容 --> <p>这是模板里的内容</p> </div> <?php return ob_get_clean(); });
之后在页面编辑器中插入[custom_page_content],API返回的content.rendered就会包含渲染后的完整内容。
方法3:自定义REST端点专门返回渲染内容
如果不想修改原有API响应,可以新建一个自定义端点,直接返回指定页面的模板渲染结果:
add_action('rest_api_init', function() { register_rest_route('custom/v1', '/page/(?P<slug>[a-zA-Z0-9-]+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => function($params) { $page = get_page_by_path($params['slug']); if (!$page) { return new WP_Error('page_not_found', '页面不存在', array('status' => 404)); } ob_start(); // 加载对应模板 get_template_part('page', $page->post_name); $rendered_content = ob_get_clean(); return array('content' => $rendered_content); } )); });
请求地址改为http://localhost:8888/wordpress/wp-json/custom/v1/page/mySlug,即可获取到完整的渲染内容。
内容的提问来源于stack exchange,提问作者user1207289
相关产品推荐
相关产品推荐

