GitHub
[gitrepo author=”f13dev” repo=”WordPress-API-PHP-class”]
Introduction
APIs are a great thing, especially if you want to access data hosted on another website. WordPress, like many other websites with a large public data store offer an API. Accessing data from an API via PHP can be a little daunting if you have little experience with functions such as curl, or little knowledge of arrays.
How to access an API
In order to access data from the WordPress API using PHP, a CURL connection needs to be created:
<?php // Initialise CURL and create a reference variable to access it $curl = curl_init(); // Create a reference variable to store the API URL to access $url = 'https://api.wordpress.org/plugins/info/1.0/YOUR_PLUGIN_SLUG.json'; // Tell CURL what URL is to be accessed curl_setopt($curl, CURLOPT_URL, $url); // Tell CURL the method to access the API, in this case GET curl_setopt($curl, CURLOPT_HTTPGET, true); // Set the user agent, this is not always required, but some APIs enforce a user agent curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); // Set CURL to return the response rather than print it curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Store the response to a variable, json_decode is used to convert the response to an array $response = json_decode(curl_exec($curl), true); // Finally close the CURL connection curl_close($curl);
Once a CURL connection has been created and the response has been stored to a variable as an array, data can be accessed via the array:
<?php // Get the name of the plugin echo $response['name']; // Get the version number of the plugin echo $response['version']; // Multi dimensional sections of the array can also be accessed and manipulated // for example the list of contributors // Create an unordered list echo '<ul>'; // For each element within the contributors array, add a list item foreach ($results['contributors'] as $key => $value) { echo '<li>' . $key . '</li>'; } // close the unordered list echo '</ul>';
An API class
As can be seen the code can become complicated, especially for those who are not familiar with arrays, the fields returned from the API or PHP. I have created a PHP class to simplify the process of accessing the WordPress plugins API:
Save the following as: wp-api.class.php
<?php class wordpress_pluing_information { // Variable to store plugin name var $slug; var $results; function wordpress_pluing_information($aSlug) { // Set the pluignName of the new object to the argument $this->slug = $aSlug; // Generate results $this->getResults(); } private function getResults() { // start curl $curl = curl_init(); // set the curl URL $url = 'https://api.wordpress.org/plugins/info/1.0/' . $this->slug . '.json'; // Set curl options curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPGET, true); // Set the user agent curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); // Set curl to return the response, rather than print it curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Get the results and store the XML to results $this->results = json_decode(curl_exec($curl), true); // Close the curl session curl_close($curl); } function getName() { return $this->results['name']; } function getSlug() { return $this->results['slug']; } function getPluginURL() { return 'https://wordpress.org/plugins/' . $this->getSlug() . '/'; } function getVersion() { return $this->results['version']; } function getAuthor() { return $this->results['author']; } function getAuthorURL() { return $this->results['author_profile']; } function getAuthorLink() { return $this->results['contributors'][0]; } function getContributorsList() { $list = '<ul>'; foreach ($this->results['contributors'] as $key => $value) { $list .= '<li><a href="' . $value . '">' . $key . '</a></li>'; } $list .= '</ul>'; return $list; } function getVersionRequired() { return $this->results['requires']; } function getVersionTestedOn() { return $this->results['tested']; } function getRating() { return $this->results['rating'] / 20; } function getRatingNumber() { return $this->results['num_ratings']; } function getRatingStars() { for ($x = 1; $x < $this->getRating(); $x++ ) { echo '<img src="img/star-full.png" />'; } if (strpos($this->getRating(), '.')) { echo '<img src="img/star-half.png" />'; $x++; } while ($x <= 5) { echo '<img src="img/star-empty.png" />'; $x++; } } function getNumberDownloads() { return $this->results['downloaded']; } function getLastUpdate() { $date = explode ('-', explode(' ', $this->results['last_updated'])[0]); $string = $date[2] . ' ' . $this->convertNumberToMonth($date[1]) . ' ' . $date[0]; return $string; } function getCreationDate() { $date = explode ('-', explode(' ', $this->results['added'])[0]); $string = $date[2] . ' ' . $this->convertNumberToMonth($date[1]) . ' ' . $date[0]; return $string; } function getBannerURL() { $baseURL = 'https://ps.w.org/' . $this->getSlug() . '/assets/banner-772x250'; if ($this->remoteFileExists($baseURL . '.jpg')) { return $baseURL . '.jpg'; } else if ($this->remoteFileExists($baseURL . '.png')) { return $baseURL . '.png'; } else { return 'img/default_banner.png'; } } function getBannerImage() { return '<img src="' . $this->getBannerURL() . '" />'; } function getIconURL() { $baseURL = 'https://ps.w.org/' . $this->getSlug() . '/assets/icon-128x128'; if ($this->remoteFileExists($baseURL . '.jpg')) { return $baseURL . '.jpg'; } else if ($this->remoteFileExists(baseURL . '.png')) { return $baseURL . '.png'; } else { return 'img/default_icon.png'; } } function getIconImage() { return '<img src="' . $this->getIconURL() . '" />'; } function getShortDescription() { return $this->results['short_description']; } function getDownloadURL() { return $this->results['download_link']; } function getDownloadLink() { return '<a href="' . $this->getDownloadURL() . '">Download</a>'; } function getTagsList() { $string = '<ul>'; foreach ($this->results['tags'] as $key => $value) { $string .= '<li>' . $value . '</li>'; } $string .= '</ul>'; return $string; } function getDonateURL() { return $this->results['donate_link']; } function getDonateLink() { return '<a href="' . $this->getDonateURL() . '">Donate</a>'; } private function convertNumberToMonth($month) { if ($month == 01) { return "January"; } else if ($month == 02) { return "February"; } else if ($month == 03) { return "March"; } else if ($month == 04) { return "April"; } else if ($month == 05) { return "May"; } else if ($month == 06) { return "June"; } else if ($month == 07) { return "July"; } else if ($month == 08) { return "August"; } else if ($month == 09) { return "September"; } else if ($month == 10) { return "October"; } else if ($month == 11) { return "November"; } else if ($month == 12) { return "December"; } else { return null; } } private function remoteFileExists($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_NOBODY, true); $result = curl_exec($curl); if ($result != false) { if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) { return true; } } else { return false; } } }
If the above code looks complicated, don’t worry it’s quite simple to use, here is an example:
<?php // First of all include the WP API file require_once('wp-api.class.php'); // Create a new object of the WP API class and store it to a variable // Replace YOUR_PLUGIN_SLUG with the slug of your plugin, e.g. 'wp-twitter-profile-widget' $wpapi = new wordpress_plugin_information('YOUR_PLUGIN_SLUG'); // Now the WP API object can be referenced via the $wpapi variable and any function not listed as private can be accessed like so: // $wpapi->aFunction(); // For example to get the name of the plugin echo $wpapi->getName(); // Or to get the version number echo $wpapi->getVersion(); // Or to create an unordered list of all the contributors echo $wpapi->getContributorsList(); // How simple is that?
Examine the code in wp-api.class.php, all of the functions which aren’t listed as private can be used with the $wpapi->aFunction(); style of code. Of course if you get stuck, need any help or have any suggestions for improvement please leave a comment.
No comments on Accessing the WordPress JSON API