This repository was archived by the owner on Nov 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Data: Loading from an API
Dan Smith edited this page May 21, 2018
·
14 revisions
DTRT WordPress Plugin Boilerplate supports Ajax API requests.
- Unstable @ 1.3.2
- Needs further testing & documentation
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'] );
}
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).
$data = $this->get_plugin_data();
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'
)