0

I've been working on a project and I just cant pull the data from this API. I'm developing a plugin that's supposed to pull data from an API and then use that data. I developed this project offline and after it was working I started developing inside the WordPress plugin space.

but for some reason i'm not getting any data.


Following is my request.

add_action( 'wp_loaded', 'precious_metals' );
function precious_metals (  ) {  
$content = file_get_contents("A WORKING API"); //Doing this for a client so hiding the API to be safe ;)

$result  = json_decode($content);
}

Following is my display(which is working offline). The table headings do display but no data is being pulled from the API.

<H4>New data fetched</H4>
    <table border = solid 1px>
        <tr>
            <td><b>Type</b></td>
            <td><b>$value</b></td>
        </tr>
    <?php foreach($result as $key=>$value): ?>
    <tr>
        <td><?php echo $key; ?></td>
        <td><?php echo $value; ?></td>
    </tr>
    <?php endforeach; ?>
</table>
  • Can you print_r($content) to see what response you are getting back from the working API?? – ChristopherJones Jun 24 '19 at 17:27
  • Yes i can and its completely empty. – Vernon van der Merwe Jun 24 '19 at 18:13
  • @ChristopherJones on my local server i get the full table back displayed with all the data i need, its just in wordpress the $content is empty – Vernon van der Merwe Jun 24 '19 at 18:14
0

Can you drop this in and let us know what $content looks like?

<?php
  $c = curl_init();
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($c, CURLOPT_URL, "A WORKING API");
  $content = curl_exec($c);
  curl_close($c);

  echo '<pre>';
  print_r($content);
  echo '</pre>';

I am curious if this is a WordPress issue or just a CORS issue with the call being made from a different host.

0

You do not need to use file_get_contents for remote request. The function that you should be looking at is wp_remote_get or wp_remote_post depending on what data you want to send to the api before receiving a response. In any case your code should be somewhat similar to:

$request  = wp_remote_get( 'http://example.com' );
$response = wp_remote_retrieve_body( $request );
if (200 !== wp_remote_retrieve_response_code( $response ))
    wp_send_json_error( $response );
wp_send_json_success( $response );

Note that wp_send_json_success/_error functions are wrappers for wp_send_json(), which includes wp_die() at the end. So you don't have to call wp_die() after wp_send_json_ functions.

Also, most of time remote APIs are sending 200 status code in general unless the api server fails to interpret your input variables in API call. So you'll still have to manually verify the result before using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.