Skip to content

Instantly share code, notes, and snippets.

@dessibelle
Last active December 23, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dessibelle/6682037 to your computer and use it in GitHub Desktop.
Save dessibelle/6682037 to your computer and use it in GitHub Desktop.
Miniature JSON API for WordPress, returning posts of a specified post type in JSON format
<?php
class WPMiniJSONAPI {
const API_ACTION_QUERY_VAR = "my-api";
const API_PERMALINK_PART = "api";
const API_EVENTS_PERMLINIK_PART = "events";
const API_OUTPUT_FORMAT = "json";
const API_EXPORT_EVENTS = "export-events";
protected $version;
public function __construct($version = 1) {
$this->version = $version;
add_action( 'init', array(&$this, 'setup_api_permalinks') );
add_action( 'wp', array(&$this, 'handle_api_request') );
}
public function setup_api_permalinks() {
global $wp;
$wp->add_query_var(self::API_ACTION_QUERY_VAR);
add_rewrite_rule(
sprintf('%s/%s/%s.%s?', self::API_PERMALINK_PART, $this->version, self::API_EVENTS_PERMLINIK_PART, self::API_OUTPUT_FORMAT),
sprintf('index.php?%s=%s&version=', self::API_ACTION_QUERY_VAR, self::API_EXPORT_EVENTS, $this->version),
'top'
);
// Will rebuild rewrite rules on each page load - don't use in production
// Instead, just load permalinks settings page once :)
if (WP_DEBUG) {
flush_rewrite_rules( $hard = true );
}
}
public function handle_api_request() {
global $wp_query;
$api_action = get_query_var( self::API_ACTION_QUERY_VAR );
if (empty($api_action))
return;
switch ($api_action) {
case self::API_EXPORT_EVENTS:
$post_type = 'event';
// It would be wise to use the WP Obejct Cache / Transients API here,
// so as not to query the database on each load.
// You could even use a really large expiration time and manually
// clear the cache when the relevant data changes.
$data = get_posts(array(
'post_type' => $post_type,
'number_posts' => -1,
'orderby' => 'date',
'order' => 'ASC',
));
global $wpdb
$mod_time = strtotime( $wpdb->query( $wpdb->prepare( "SELECT MAX(post_modified_gmt) FROM $wpdb->posts WHERE post_type %s", $post_type ) ) );
if ($mod_time) {
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $mod_time ) . ' GMT' );
}
header('Content-Type: application/json; charset=utf8');
echo json_encode($data);
exit();
break;
}
}
}
$api = new WPMiniJSONAPI();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment