Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.