Skip to content

Instantly share code, notes, and snippets.

@iainmcampbell
Forked from petenelson/page-api.php
Last active August 29, 2015 14:19
Show Gist options
  • Save iainmcampbell/7cbaeca633ec0be2be7b to your computer and use it in GitHub Desktop.
Save iainmcampbell/7cbaeca633ec0be2be7b to your computer and use it in GitHub Desktop.
<?php
/*
Using WordPress as a REST API endpoint (vs AJAX Admin)
-- with caching using the Transient API --
forked from: Pete Nelson @GunGeekATX
1) Create a page called API in WordPres
2) Create a file called page-api.php in your theme directory
3) Build custom endpoints
*/
// Call the API by sending a POST request to this page, with an 'action' parameter
// from Angular, which sends POST requests in JSON format:
// $http.post('http://localhost/wp-mysite/api', { action: 'home' })
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
// from anything else that sends its POST requests old school:
// POST http://localhost/wp-mysite/api/?action=list-all-pages
// $.post('http://localhost/wp-mysite/api', {action:'list-all-pages'})
// $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
$output = null;
$api = new API();
switch ($action) {
case 'list-all-pages':
$output = $api->list_all_pages();
break;
default:
$output = array('error' => 'invalid action');
break;
}
if ($output) {
header("Content-Type: application/json");
echo json_encode($output);
}
die();
// ********************************************************
class API {
function cached_hello_world(){
$KEY = "hello_world";
// try to fetch the response from cache
// this will fail if the cache is out of date
$response = get_transient($KEY);
if($response) return json_decode($response);
// build our response
$response = new stdClass();
$response->data = 'Hello World!';
// save response to cache, with an expiry date (HOUR_IN_SECONDS)
set_transient($KEY, json_encode($response), HOUR_IN_SECONDS);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment