Last active
August 29, 2015 14:22
-
-
Save rmccue/99df1e545bd8bf45c9b8 to your computer and use it in GitHub Desktop.
Demo code from WC talk - Requires v2 of the REST API
This file contains 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 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