Skip to content

Instantly share code, notes, and snippets.

@Christian-Roth
Last active November 15, 2016 11:39
Show Gist options
  • Save Christian-Roth/c3af4ac880036ea2a3e2a1c3579ae89a to your computer and use it in GitHub Desktop.
Save Christian-Roth/c3af4ac880036ea2a3e2a1c3579ae89a to your computer and use it in GitHub Desktop.
Functions to add a custom route to the WP REST API
// Init REST Route
function register_custom_api_hooks() {
$namespace = 'custom-name/v1';
register_rest_route( $namespace, '/posts/', array(
'methods' => 'GET',
'callback' => 'custom_api_get_posts',
) );
}
add_action( 'rest_api_init', 'register_custom_api_hooks' );
// Callback Function to get posts
function custom_api_get_posts() {
$args = array(
'numberposts' => 10,
'post_type' => 'post',
'post_status' => 'publish',
);
$all_posts = get_posts( $args );
$return = array();
foreach ( $all_posts as $post ) {
$return[] = array(
'ID' => $post->ID,
'title' => $post->post_title,
'permalink' => get_permalink( $post->ID ),
);
}
$response = new WP_REST_Response( $return );
$response->header( 'Access-Control-Allow-Origin', '*' );
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment