【问题标题】:Wordpress REST API - Write to JSON File?Wordpress REST API - 写入 JSON 文件?
【发布时间】:2017-10-02 21:44:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: php wordpress wordpress-rest-api


    【解决方案1】:

    我找到了 3 种不同的方法来解决这个问题,所有这些方法都在 Stackoverflow 上,但我会选择 Tanner 开始的那个,刚刚完整发布:

    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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

      // 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

      【讨论】:

      • 这个答案应该被接受,因为它增强了现代 WP 标准并且很灵活。
      • 是的,看起来很整洁。
      【解决方案3】:

      按照更准确的答案,我将函数包装到自己的容器中,因此有一个标准的动作/函数结构。

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

      【讨论】:

        【解决方案4】:

        你应该能够按照这些思路完成一些事情。查看下面的代码:

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

        这应该在每次发布时保存一个 json 文件。我相信您可以修改它以导出您网站所需的所有数据。

        【讨论】:

        • 这个答案给了我正确的方向,尽管中间缺失的部分可以完全分享。谢谢!
        猜你喜欢
        • 1970-01-01
        • 2016-12-30
        • 2021-10-31
        • 1970-01-01
        • 2014-12-23
        • 1970-01-01
        • 2018-01-09
        • 2016-08-13
        • 2019-10-06
        相关资源
        最近更新 更多