wpDataTables is a popular tables plugin for WordPress that can create amazing looking tables and charts. We can use the free version of this plugin and integrate it with WPGetAPI to build tables and charts from an API. The free version can be downloaded here.
The examples we use in this article are real world examples so you can actually set this up on your own site and test it out. We are using the Quotable API which can be found here.
Add the API
The first step is to add a new API within the Setup page.
Add the endpoint
We are using the ‘quotes’ endpoint which returns a big list of quotes – https://github.com/lukePeavey/quotable#list-quotes
When setting up your endpoint, the main thing to be sure of is that the Results Format setting is set to PHP array data as this will return the data in an array format that can be used with the wpDataTables plugin.
We have also set the limit to 5 which tells the API to only get us 5 quotes. We have also set the cache time to 60 seconds just to avoid hitting the API too often.
Writing the code
We are following the docs from the wpDataTables website here – https://wpdatatables.com/documentation/creating-wpdatatables/creating-wpdatatables-from-serialized-php-array/
First we need to create a PHP file at the root directory of our website – we named ours wpgetapi-table.php and then added the below code.
<?php
// Initializing the WordPress engine in a stanalone PHP file
include('wp-blog-header.php');
header("HTTP/1.1 200 OK"); // Forcing the 200 OK header as WP can return 404 otherwise
$data = wpgetapi_endpoint( 'quotable', 'quotes', array('debug' => false) );
$return_array = array();
if( isset( $data['results'] ) && is_array( $data['results'] ) ) {
// loop through each item in the results array
foreach ( $data['results'] as $i => $item ) :
$return_array[] = array(
'Author' => $item['author'],
'Quote' => $item['content'],
'ID' => $item['_id']
);
endforeach;
}
echo serialize( $return_array );
Setup wpDataTables
Now we simply need to create a new table within wpDataTables:
We then set the URL to be our new file: