Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rmccue
Last active August 29, 2015 14:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmccue/99df1e545bd8bf45c9b8 to your computer and use it in GitHub Desktop.
Save rmccue/99df1e545bd8bf45c9b8 to your computer and use it in GitHub Desktop.
Demo code from WC talk - Requires v2 of the REST API
<?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 new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>.+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function ( $val ) { return is_numeric( $val ); },
),
),
'permission_callback' => function () {
return current_user_can( 'manage_options' );
}
) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment