Created
December 1, 2016 21:55
-
-
Save collegeman/c5983be03108002abeda060408b8bcd9 to your computer and use it in GitHub Desktop.
Defining a custom REST API endpoint in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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