FORSMILE
JA
WordPress2020/08/05

[WORDPRESS] Displaying Data Retrieved from an External API in a Post

When I started writing game articles, I thought it would be easier to retrieve basic app information from an API.

Back to Blog

When I started writing game articles, I thought it would be easier to retrieve basic app information from an API.

The basic app information on the page below is displayed using data retrieved from an API.

Since I use an iPhone, I initially thought just iOS information would be sufficient. When I looked it up, I found an API like this.

I'd like to try displaying the above information on a WordPress post.

RETRIEVING DATA FROM AN EXTERNAL API USING CURL IN PHP

While you can also retrieve data from external APIs using JavaScript, this time we'll implement it using PHP's cURL.

There's also a WordPress function called `wp_remote_get`. I'll just mention it briefly here.

We'll be writing this in `functions.php`, but to prevent changes from being lost during updates, let's create a child theme first.

[WORDPRESS] Preventing Changes from Being Overwritten During Theme Updates

We'll create a shortcode to make it easy to use within post content.

[WORDPRESS] How to Create and Use New Shortcodes

javascript
function getAppInfo($atts = array()) {
  shortcode_atts(array(
    'id' => '',
    'lang' => ''
  ), $atts);
  $url = "https://itunes.apple.com/lookup?id=" . $atts['id'] . "&country=" . $atts['lang'];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);
  $result = json_decode($response);
  $appInfoData = $result->results[0];
 ・・・・・
}
add_shortcode('appinfo', 'getAppInfo');

We'll use 'id' and 'lang', obtained from the shortcode attributes, to generate the `$url` for the API request.

The 'id' part is the app ID (you can find it in the URL query when you search for an app on the iTunes site).

'lang' is the display language. Use 'JP' for Japanese, 'US' for American English.

cURL Part

`curl_setopt`... Specifies options for the cURL execution.

`CURLOPT_RETURNTRANSFER`... Receives the execution data as a string.

We use `json_decode` to convert the received JSON string data into a PHP variable so it can be used in PHP.

Data retrieval is now complete. Next, we'll display the retrieved data.

DISPLAYING DATA RETRIEVED FROM AN API IN A WORDPRESS POST

For clarity, I've written the code directly within `functions.php` this time.

javascript
<?php
function getAppInfo($atts = array()) {
  shortcode_atts(array(
    'id' => '',
    'lang' => ''
  ), $atts);
  $url = "https://itunes.apple.com/lookup?id=" . $atts['id'] . "&country=" . $atts['lang'];

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);
  $result = json_decode($response);
  $appInfoData = $result->results[0];
  ob_start();
  ?>
    <div class="app-info-name">
      <a href="<?php echo $appInfoData->trackViewUrl; ?>" target="_blank" rel="noopener"><?php echo $appInfoData->trackName; ?></a>
    </div>
  <?php
  return ob_get_clean();
}
add_shortcode('appinfo', 'getAppInfo');
?>

You can check other received data by using `var_dump(appInfoData);`.

The sample below displays data for a game called 'Archero'.

text
[appinfo id=1453651052 lang=JP]

As a side note, if an API can be fetched with `wp_remote_get`, it's easier to use that.

For some reason, the iTunes API only returned a partial body when I tried, so I switched to cURL.

It's possible that `wp_remote_get` might be able to retrieve it with specific options.

RECOMMENDED WORDPRESS BOOKS

I tend to read books, but I truly feel that you learn more deeply by actually implementing things.

I recommend reading books on WordPress itself and on PHP.

Knowing HTML and CSS would broaden your possibilities, but the great thing about WordPress is that you can manage the design aspects just by relying on templates.

The Easiest WordPress Introduction Course (Japanese) Paperback

WordPress basics. It carefully explains everything from installation.

There are many books available, so any would be fine, but I chose this one because it's recently published and the author is beautiful.

For those who are serious about development. It introduces practical examples, so it can also be used for brainstorming ideas.

📦
Amazon で関連書籍・ツールを検索
WordPress development book
Amazonで探す →(アソシエイトリンク)