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

  1. Log in to your WordPress admin dashboard.
  2. Navigate to “Plugins” > “Add New.”
  3. Search for “Code Snippets.”
  4. 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

  1. Go to “Snippets” in the WordPress dashboard.
  2. Click on “Add New” to create a new code snippet.
  3. Provide a title for your snippet, such as “cURL API Request.”
  4. 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

  1. Create a new page or edit an existing one where you want to display the API data.
  2. 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

  1. Go back to the “Code Snippets” section.
  2. 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

  1. Visit the page where you added the shortcode.
  2. You should now see the JSON data retrieved from the API displayed on the page.

Related Posts