Skip to content

Instantly share code, notes, and snippets.

@collegeman
Created December 1, 2016 21:55
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 collegeman/c5983be03108002abeda060408b8bcd9 to your computer and use it in GitHub Desktop.
Save collegeman/c5983be03108002abeda060408b8bcd9 to your computer and use it in GitHub Desktop.
Defining a custom REST API endpoint in WordPress
<?php
/**
* Grab latest post title by an author!
*
* @param array $data Options for the function.
* @return string|null Post title for the latest,
 * or null if none.
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment