Wordpress REST API - 写入 JSON 文件? [英] Wordpress REST API - Write to JSON File?

查看:29
本文介绍了Wordpress REST API - 写入 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Wordpress REST API,并创建了我的自定义端点,并获取了我想要的确切数据.基本上,我创建了一个端点来接收我所有的帖子/页面/acf - 而不是在每个页面加载时调用 API,我只想在我的预加载器期间调用一次 API.

I've been messing around with the Wordpress REST API, and created my custom endpoint, and getting the exact data I want. Basically I created an endpoint to receive all my post/pages/acf - Instead of calling the API on each page load, I just wanted to call the API once during my preloader.

但是,当我调用 API 时,所有逻辑都会运行,这会导致加载时间为 1 到 2 秒.是否有可能每当我在 Wordpress 上进行更新时,它都会调用我的端点,并在服务器上写入一个 JSON 文件,即 data.json?这样,当我加载我的网站时,它可以调用那个 data.json,完全没有延迟.

However, when I call the API, all the logic runs, which then causes a loading time of 1 to 2 seconds. Is there a possibility that whenever I make an update on Wordpress, it will call my endpoint, and write a JSON file on the server, so data.json? This way, when I load my site, it can call that data.json, with absolutely no delay at all.

我不确定这是否可行,但想尝试在这里提问.

I'm not sure if this is possible but wanted to try asking here.

推荐答案

此方法允许您从外部或内部 API 端点编写 json;它不像上面的那样复杂(目标文件夹明智),但使用 REST API,因此您无需指定所有字段即可获取完整的帖子对象:

This method allow you to write a json from and external or internal API endpoint; it is less sofisticated than the one above (destination folder wise), but uses the REST API so you can fetch the full posts object without having to specify all the fields:

// Export API Data to JSON, another method
add_action('publish_post', function ($ID, $post) {

    $wp_uri = get_site_url();
    $customApiEndpoint = '/wp-json/wp/v2/posts'; // or your custom endpoint

    $url = $wp_uri . $customApiEndpoint; // outputs https://your-site.com/wp-json/wp/v2/posts
    // $url = 'https://your-site.com/wp-json/wp/v2/posts'; // use this full path variable in case you want to use an absolute path

    $response = wp_remote_get($url);
    $responseData = json_encode($response); // saved under the wp root installation, can be customized to any folder

    file_put_contents('your_api_data_backup.json', $responseData);

}, 10, 2);

灵感来自 https://stackoverflow.com/questions/46082213/wordpress-save-api-json-after-publish-a-post

这篇关于Wordpress REST API - 写入 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆