Wordpress Cron - Call External API - Save JSON File

Viewed 321

i thought i would reach out to get some guidance on a little thing i am working on.

What i would like to do within Wordpress:

  • Call external API (with token header)
  • Get the results of the api and save it into a file in wpallimport's upload folder

I would assume i can just make a simple WP plugin and within the 'activate' hook for the plugin:

  • create a wp-cron (as i would like it to run every day) for the following:

    $url = 'the-api-url';
    
    $data = wp_remote_get( $url ,
         array('headers' => array( 'Token' => 'tokenkey')
         ));
    
    $jsonfile = $data['body'];
    
    global $wp_filesystem;
    
    if (empty($wp_filesystem)) {
        require_once (ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }
    
    $file = '/wp-content/uploads/wpallimport/files/JSONFILE.JSON';
    
    $wp_filesystem->put_contents($file, $jsonfile);
    

However i am not having success with the above (with the correct API url and token etc obviously)

Thanks in advance!

0 Answers
Related