我正在构建一个使用 WordPress
作为 CMS 的 Backbone.js
网站。 Backbone
应用程序配置为使用来自 WP REST API 的 JSON。我想通过从 WP 主题输出来引导初始页面加载的 post JSON。我希望能够做的是这样的:
$postsJSON = [];
$restResponse = new WP_REST_Response();
$restRequest = new WP_REST_Request();
while (have_posts()) { the_post();
$postsJSON[] = apply_filters('rest_prepare_post', $restResponse, $post, $restRequest);
}
echo "<script type='application/json'>[" . join(",", $postsJSON) . "</script>";
但是这段代码不起作用。我只是得到一个空的 WP_REST_Response
。是否有更简单的方法将 $post
对象转换为 REST-API 格式的 JSON?
最佳答案
我想出了这个。这种方法仍有改进的空间,但现在对我来说已经足够好了:
<?php
$postsJSON = [];
$restControllers = [];
$restRequest = new WP_REST_Request();
while (have_posts()) { the_post();
if (!isset($restControllers[$post->post_type])) {
$restControllers[$post->post_type] = new WP_REST_Posts_Controller($post->post_type);
}
$preparedPost = $restControllers[$post->post_type]->prepare_item_for_response($post, $restRequest);
$postsJSON[] = json_encode($preparedPost->data);
}
?>
<script id="data-posts" type="application/json">
[<?php echo join(",", $postsJSON); ?>]
</script>
此方法的潜在问题:
- 在某些情况下可能需要使用不同的
WP_REST_Posts_Controller
。 - 使用
WP_REST_Request
的空实例可能会产生意想不到的后果。
关于php - WP $post 对象可以从主题文件输出为 REST-API 格式的 JSON 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499297/