How to Showcase JSON Data from API on Your WordPress Site Using cURL
Here’s a step-by-step guide on how to show JSON data from an API using cURL in WordPress:
Step 1: Install and Activate Custom Functions Plugin
- Log in to your WordPress admin dashboard.
- Navigate to “Plugins” > “Add New.”
- Search for “Code Snippets.”
- Install and activate the “Code Snippets” plugin. This plugin allows you to add custom PHP code snippets without modifying your theme’s files.
Step 2: Add cURL Functionality via Code Snippets
- Go to “Snippets” in the WordPress dashboard.
- Click on “Add New” to create a new code snippet.
- Provide a title for your snippet, such as “cURL API Request.”
- In the code editor, add the following PHP code:
function get_api_data_via_curl() { $api_url = 'https://api.example.com/data'; // Replace with your API endpoint $curl = curl_init($api_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $api_response = curl_exec($curl); curl_close($curl); $api_data = json_decode($api_response, true); return $api_data; }
Replace ‘https://api.example.com/data’ with the actual URL of the JSON API you want to fetch.
Save the snippet.
Step 3: Display API Data in a WordPress Page or Post
- Create a new page or edit an existing one where you want to display the API data.
- Add a shortcode to fetch and display the data. Update the shortcode to match your function name.
[api_data_shortcode]
Save or update the page.
Step 4: Add Shortcode Functionality
- Go back to the “Code Snippets” section.
- Create a new snippet with the following code:
function display_api_data_shortcode() { $api_data = get_api_data_via_curl(); // Display the data as needed echo ''; print_r($api_data); echo '';
}
add_shortcode('api_data_shortcode', 'display_api_data_shortcode');This function fetches the API data using cURL and displays it using a shortcode. Save the snippet.
Step 5: View the Page
- Visit the page where you added the shortcode.
- You should now see the JSON data retrieved from the API displayed on the page.