Step-by-Step Guide to Create a WordPress Plugin for Fetching and Displaying Remote XML Data
1. Create a New Plugin Directory
- Connect to your WordPress installation via FTP or use the file manager in your hosting control panel.
- Navigate to
wp-content/plugins/
.
- Create a new directory named
remote-xml-fetch
.
2. Create the Plugin File
- Inside the
remote-xml-fetch
directory, create a new file named remote-xml-fetch.php
.
3. Add Plugin Header
- Open
remote-xml-fetch.php
in a text editor and add the following plugin header:
<?php
/**
* Plugin Name: Remote XML Fetch and Display
* Description: Fetches remote XML data and displays it on a WordPress page.
* Version: 1.0
* Author: Your Name
*/
4. Add Function to Fetch XML Data
- Below the plugin header, add the following PHP function to fetch and process the XML data:
function fetch_remote_xml_data() {
$yesterday = date('d-M-y', strtotime('-1 day'));
$url = "https://<sanitized site and directories>/<filename>.xsql?stn=&sig=LOC&type=&start={$yesterday}&end={$yesterday}&time=&priority=&fmodel=&sort=&ndays=&user=";
$response = wp_remote_get($url);
if ( is_wp_error($response) ) {
return 'Failed to fetch data.';
}
$body = wp_remote_retrieve_body($response);
if ( empty($body) ) {
return 'No data retrieved.';
}
$xml = simplexml_load_string($body);
if ( $xml === false ) {
return 'Failed to parse XML.';
}
// Process and display the XML data
$output="<table id="myTable"><tr><th>Number</th><th>Name</th><th>Latitude</th></tr>";
foreach ( $xml->row as $row ) {
$number = $row->firstField;
$name = $row->secondField;
$lat = $row->thirdField;
$output .= "<tr><th>{$number}</th><td>{$name}</td><td>{$lat}</td></tr>";
}
$output .= '</table>';
return $output;
}
5. Create a Shortcode to Display the Data
- Add the following function to create a shortcode that displays the fetched XML data:
function display_remote_xml_data() {
return fetch_remote_xml_data();
}
add_shortcode('display_xml_data', 'display_remote_xml_data');
6. Save and Upload the Plugin File
- Save the changes to
remote-xml-fetch.php
.
- Upload the
remote-xml-fetch.php
file to the remote-xml-fetch
directory on your WordPress server if you edited it locally.
7. Activate the Plugin
- Log in to your WordPress admin dashboard.
- Navigate to
Plugins
.
- Find
Remote XML Fetch and Display
in the list and click Activate
.
8. Use the Shortcode in a Post or Page
- Edit the post or page where you want to display the XML data.
- Add the following shortcode where you want the data to appear:
[display_xml_data]
9. Verify the Output
- View the post or page to ensure the XML data is fetched and displayed correctly in a table.