Data: Loading from an API - dotherightthing/wpdtrt-plugin-boilerplate GitHub Wiki
Summary
DTRT WordPress Plugin Boilerplate supports Ajax API requests.
Status
- Unstable @ 1.3.2
- Needs further testing & documentation
Usage
Request data from API
To implement an API request to your own plugin, use the (plugin_name)_set_api_endpoint
filter to specify the endpoint (URL) to use when requesting data from an API.
Example from DTRT Forms:
Create the filter function:
/**
* Set the API endpoint
* The filter is applied in wpplugin->get_api_data()
*
* @return string $endpoint
*
* @since 1.3.4
*
* @example
* add_filter( 'wpdtrt_forms_set_api_endpoint', [$this, 'filter_set_api_endpoint'] );
*/
public function filter_set_api_endpoint() {
$plugin_options = $this->get_plugin_options();
$endpoint = '';
if ( key_exists('value', $plugin_options['template']) ) {
$template = $plugin_options['template']['value'];
$endpoint = ( WPDTRT_FORMS_URL . 'data/form-' . $template . '.json' );
}
return $endpoint;
}
Add the filter in wp_setup()
:
protected function wp_setup() {
parent::wp_setup();
// add actions and filters here
add_filter( 'wpdtrt_forms_set_api_endpoint', [$this, 'filter_set_api_endpoint'] );
}
Triggering a call to the API
API data is loaded via Ajax when the plugin settings are saved via the Settings page (assuming that an API key has been supplied in the provided form field).
Get saved data
$data = $this->get_plugin_data();
Data is stored in an associative array
Example response $data
from API:
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "http://placehold.it/600/92c952",
"thumbnailUrl": "http://placehold.it/150/92c952"
}
$data
as an associative array:
Array (
'albumId' => 1
'id' => 1
'title' => 'accusamus beatae ad facilis cum similique qui sunt'
'url' => 'http://placehold.it/600/92c952'
'thumbnailUrl' => 'http://placehold.it/150/92c952'
)