Certainly! Here’s an example of a WordPress plugin that calls an API and displays its content:
<?php
/*
Plugin Name: API Content Display
Plugin URI: https://www.example.com
Description: A WordPress plugin to call an API and display its content.
Version: 1.0
Author: Your Name
Author URI: https://www.example.com
License: GPLv2 or later
*/
// Register a shortcode to display the API content
add_shortcode('api_content', 'display_api_content');
function display_api_content($atts) {
// API endpoint URL
$api_url = 'https://api.example.com/data';
// Make the API request
$response = wp_remote_get($api_url);
// Check if the API request was successful
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return 'Failed to retrieve API data.';
}
// Get the API response body
$data = wp_remote_retrieve_body($response);
// Decode the JSON response
$decoded_data = json_decode($data, true);
// Display the API content
$content = '';
if ($decoded_data && is_array($decoded_data)) {
foreach ($decoded_data as $item) {
$content .= '<div>';
$content .= '<h2>' . esc_html($item['title']) . '</h2>';
$content .= '<p>' . esc_html($item['description']) . '</p>';
$content .= '</div>';
}
}
return $content;
}
Here’s how to use the plugin:
- Create a new directory in the
wp-content/plugins
directory of your WordPress installation and name itapi-content-display
. - Create a new PHP file in the
api-content-display
directory and name itapi-content-display.php
. - Copy and paste the above code into the
api-content-display.php
file. - Save the file.
- Activate the plugin from the WordPress admin panel.
- Now you can use the
[api_content]
shortcode in your WordPress posts or pages to display the content from the API.
For example, you can create a new post or page and use the shortcode like this:
[api_content]
When the post or page is viewed, the plugin will make a request to the specified API endpoint, retrieve the content, and display it in the post or page.
Please note that this is a basic example, and you may need to modify it based on your specific API requirements.