Skip to content

Instantly share code, notes, and snippets.

@shanaver
Created April 2, 2014 22:18
Show Gist options
  • Save shanaver/9944384 to your computer and use it in GitHub Desktop.
Save shanaver/9944384 to your computer and use it in GitHub Desktop.
Basic Wordpress JSON REST API Custom Post Type Example
<?php
/*
* Notes:
*
* activate the json-rest-api plugin - then add this code to your functions.php file
*
* now the following ajax call should work:
*
jQuery.ajax({
url : 'http://localhost/wp-json.php/projects',
type: 'GET',
});
*
*/
if (class_exists('WP_JSON_CustomPostType'))
{
class WP_JSON_Projects extends WP_JSON_CustomPostType
{
/**
* Base route name
*
* @var string Route base (e.g. /my-plugin/my-type)
*/
protected $base = '/projects';
/**
* Associated post type
*
* @var string Type slug
*/
protected $type = 'projects';
public function registerRoutes( $routes ) {
$post_routes = array(
'/projects' => array(
array( array( $this, 'getPosts' ), WP_JSON_Server::READABLE ),
)
);
return array_merge( $routes, $post_routes );
}
}/* end class */
function json_api_project_filters($server) {
global $wp_json_posts, $wp_json_pages, $wp_json_media, $wp_json_taxonomies;
$wp_json_projects = new WP_JSON_Projects($server);
add_filter( 'json_endpoints', array( $wp_json_projects, 'registerRoutes' ), 0 );
}
add_action( 'wp_json_server_before_serve', 'json_api_project_filters', 10, 1 );
}/* end if */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment