Guide to displaying data from an external API in WordPress using a shortcode:
1. Create a Shortcode in functions.php
Create a shortcode in your functions.php
file that outputs a container for the results and includes a JavaScript file:
function fetch_external_api_data() {
wp_enqueue_script('custom-api-fetch-script');
return '<div id="apiResults"></div>';
}
add_shortcode('external_api_data', 'fetch_external_api_data');
2. Enqueue and Write JavaScript
Create api-fetch.js
in your theme directory to fetch and display the data:
function enqueue_custom_scripts() {
wp_register_script('custom-api-fetch-script', get_template_directory_uri() . '/js/api-fetch.js', array('jquery'), null, true);
wp_localize_script('custom-api-fetch-script', 'apiSettings', array('apiUrl' => 'URL_OF_YOUR_API'));
wp_enqueue_script('custom-api-fetch-script');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
In api-fetch.js
, use AJAX to get the data and render it:
jQuery(document).ready(function($) {
$.get(apiSettings.apiUrl, function(data) {
var content = data.listOfResults.map(item => '<div>' + item.title + '</div>').join('');
$('#apiResults').html(content);
});
});
3. Use the Shortcode
Place [external_api_data]
in any post, page, or widget to display the API results.
This method uses a JavaScript-based approach to render the API data dynamically on the client side, similar to React, and integrates easily with existing WordPress widgets like those in Elementor via shortcodes.