Skip to content

Instantly share code, notes, and snippets.

@mckernanin
Created August 6, 2016 18:20
Show Gist options
  • Save mckernanin/fbcf4545b148a14283ba3d142780d31f to your computer and use it in GitHub Desktop.
Save mckernanin/fbcf4545b148a14283ba3d142780d31f to your computer and use it in GitHub Desktop.
REST API Endpoint Example
<?php
add_action( 'rest_api_init', 'spe_register_api_hooks' );
function spe_register_api_hooks() {
$namespace = 'simple-posts/v1';
register_rest_route( $namespace, '/list-posts/', array(
'methods' => 'GET',
'callback' => 'spe_get_posts',
) );
}
function spe_get_posts() {
if ( 0 || false === ( $return = get_transient( 'spe_all_posts' ) ) ) {
$query = apply_filters( 'spe_get_posts_query', array(
'numberposts' => 10,
'post_type' => 'post',
'post_status' => 'publish',
) );
$all_posts = get_posts( $query );
$return = array();
foreach ( $all_posts as $post ) {
$return[] = array(
'ID' => $post->ID,
'title' => $post->post_title,
'permalink' => get_permalink( $post->ID ),
);
}
// cache for 10 minutes
set_transient( 'spe_all_posts', $return, apply_filters( 'spe_posts_ttl', 60 * 10 ) );
}
$response = new WP_REST_Response( $return );
$response->header( 'Access-Control-Allow-Origin', apply_filters( 'spe_access_control_allow_origin', '*' ) );
return $response;
}
var apiPath = 'https://mckernan.in/wp-json/simple-posts/v1/list-posts',
$.ajax({
type : 'GET',
url : apiPath,
async : true,
dataType : 'json',
success : function(result) {
console.log('Woohoo! We got some posts!');
console.log(result);
},
fail : function(result) {
console.log('Oh no! Something went wrong!');
console.log(result);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment