Wordpress REST API - Write to JSON File?

此生再无相见时 提交于 2020-05-16 05:10:48

问题


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.

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.


回答1:


I found 3 different ways to address the question, all of them here on Stackoverflow, but I'll go with the one that Tanner started, just published in full:

function export_posts_in_json() {
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

    $query = new WP_Query($args);
    $posts = array();

    while ($query->have_posts()): $query->the_post();
        $posts[] = array(
            'title' => get_the_title(),
            'excerpt' => get_the_excerpt(),
            'author' => get_the_author(),
            // any extra field you might need
        );
    endwhile;

    wp_reset_query();
    $data = json_encode($posts);
    $upload_dir = wp_get_upload_dir(); // set to save in the /wp-content/uploads folder
    $file_name = date('Y-m-d') . '.json';
    $save_path = $upload_dir['basedir'] . '/' . $file_name;

    $f = fopen($save_path, "w"); //if json file doesn't gets saved, comment this and uncomment the one below
    //$f = @fopen( $save_path , "w" ) or die(print_r(error_get_last(),true)); //if json file doesn't gets saved, uncomment this to check for errors
    fwrite($f, $data);
    fclose($f);
}

add_action('save_post', 'export_posts_in_json');

Original snippet here: https://wordpress.stackexchange.com/questions/232708/export-all-post-from-database-to-json-only-when-the-database-gets-updated

Hope this helps.




回答2:


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);

inspired from https://stackoverflow.com/questions/46082213/wordpress-save-api-json-after-publish-a-post




回答3:


You should be able to accomplish something along those lines. Check out the code below:

function export_posts_in_json () {

  $args = array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
  );

  $query = new WP_Query( $args );

  ...

  $data = json_encode($posts);

  $folder = 'YOUR_EXPORT_PATH_HERE';
  $file_name = date('Y-m-d') . '.json';
  file_put_contents($folder.$file_name, $data);
}

add_action( 'save_post', 'export_posts_in_json' );

This should save a json file every time a post is made. I'm sure you can modify it to export all the data you need for your site.




回答4:


Following up the more accuarate answer, I wrapped the function into its own container so there is a standard action/function structure.

// Export API Data to JSON, another method
add_action('publish_post', 'export_wp_rest_api_data_to_json', 10, 2);

function export_wp_rest_api_data_to_json($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);
}


来源:https://stackoverflow.com/questions/43787499/wordpress-rest-api-write-to-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!