To display custom data on your WordPress website after making an API call, you can use a plugin or create a custom solution using PHP and JavaScript.
Option 1: Using a plugin There are several plugins available for WordPress that allow you to make API calls and display data on your website. One popular plugin is "WP REST API Controller". It enables you to connect to various APIs and display the data on your WordPress site using shortcodes.
Here's how to use it:
- Install and activate the WP REST API Controller plugin from your WordPress admin panel.
- Navigate to "Settings" > "WP REST API Controller" in the WordPress admin panel.
- Configure the plugin settings, such as authentication and endpoints.
- Create a new post or page, and use the provided shortcodes to display the data on your website.
Option 2: Creating a custom solution
You can create a custom solution using PHP and JavaScript to fetch data from an API and display it on your WordPress site.
- Create a new page template in your WordPress theme folder (e.g.,
page-custom-api-data.php
). Add the following code to the top of the file to make it a page template:
php<?php
/*
Template Name: Custom API Data
*/
?>
- Write the PHP code to make the API call using
wp_remote_get()
orcURL
. Parse the response, and store it in a variable that you can pass to your view.
php<?php
$response = wp_remote_get( 'https://api.example.com/data' );
if ( is_array( $response ) && ! is_wp_error( $response ) ) {
$data = json_decode( $response['body'], true );
} else {
$data = null;
}
?>
- In the same file, write the HTML and PHP code to display the data:
html<?php get_header(); ?>
<main>
<?php if ( $data ): ?>
<div id="custom-api-data">
<!-- Display your custom data here, e.g., using a loop -->
</div>
<?php else: ?>
<p>Error fetching data from the API.</p>
<?php endif; ?>
</main>
<?php get_footer(); ?>
- Create a new page in your WordPress admin panel and assign the "Custom API Data" template to it. Publish the page and visit it to see the custom data displayed on your site.
With this custom solution, you can modify the code to fetch data from any API and display it as needed on your WordPress site.