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