0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

How to Display External API Data in WordPress Using a Custom Shortcode

0
Posted at

How to Display External API Data in WordPress Using a Custom Shortcode

WordPress shortcodes are useful when we need to display dynamic data inside posts or pages without editing the theme template directly.

In this example, we will create a simple shortcode that retrieves JSON data from an external API and displays the result in WordPress.

Why Use a Shortcode?

A shortcode allows us to place dynamic content anywhere in WordPress using a simple syntax such as:

[external_data]

This approach is useful for dashboards, statistics, schedules, public data, and other information that changes regularly.

Create the Shortcode

Add the following PHP code to a custom plugin or your development environment.

function my_external_data_shortcode() {

    $response = wp_remote_get(
        'https://example.com/api/data',
        array(
            'timeout' => 10
        )
    );

    if (is_wp_error($response)) {
        return 'Unable to retrieve data.';
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (!$data) {
        return 'No data available.';
    }

    $output = '<div class="external-data">';

    foreach ($data as $item) {
        $output .= '<p>';
        $output .= esc_html($item['name']);
        $output .= '</p>';
    }

    $output .= '</div>';

    return $output;
}

add_shortcode('external_data', 'my_external_data_shortcode');
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?