php - WP $post 对象可以从主题文件输出为 REST-API 格式的 JSON 吗?

标签 php json wordpress rest wordpress-rest-api

我正在构建一个使用 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>

此方法的潜在问题:

  1. 在某些情况下可能需要使用不同的 WP_REST_Posts_Controller
  2. 使用 WP_REST_Request 的空实例可能会产生意想不到的后果。

关于php - WP $post 对象可以从主题文件输出为 REST-API 格式的 JSON 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499297/

相关文章:

php - 为什么我不能用 foreach 循环更新数组中的数据?

php - 从PHP中的Sqlcipher加密数据库中选择行

JSON 中的 Javascript 数组不起作用

php - 在 Woocommerce 交易电子邮件中显示产品 ACF 字段值

ruby-on-rails-3 - 在 WordPress 博客和 RoR 应用程序之间共享登录状态?

php - 时隙重叠

javascript - jquery .autocomplete 仅显示集合中的最后一条记录

php - 通过 JSON、JQuery、PHP 传递特定信息

jquery - 排除从 jQuery 外部文件附加的外部样式表

php - 记录唯一文章浏览次数的最有效方法是什么