tomazsaraiva
5/7/2018 - 9:51 AM

Wordpress REST API Basics

/**
 * Rest API Initialization
 * The place to add custom endpoints and fields
 */
add_action('rest_api_init', function () {

    /*
    * Register custom field
    register_rest_field( 'comment', 'karma', array(
        'get_callback' => function( $comment_arr ) {
            $comment_obj = get_comment( $comment_arr['id'] );
            return (int) $comment_obj->comment_karma;
        },
        'update_callback' => function( $karma, $comment_obj ) {
            $ret = wp_update_comment( array(
                'comment_ID'    => $comment_obj->comment_ID,
                'comment_karma' => $karma
            ) );
            if ( false === $ret ) {
                return new WP_Error(
                  'rest_comment_karma_failed',
                  __( 'Failed to update comment karma.' ),
                  array( 'status' => 500 )
                );
            }
            return true;
        },
        'schema' => array(
            'description' => __( 'Comment karma.' ),
            'type'        => 'integer'
        ),
    ));
    */

    register_rest_route('bavidros/v1', '/author', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
        'permission_callback' => function () {
            return current_user_can('edit_others_posts');
        },
        'args' => array(
            'id' => array(
                'default' => 1,
                'required' => true,
                'validate_callback' => function ($param, $request, $key) {
                    return is_numeric($param);
                }
            ),
        ),
    ));
});

/** Adding a custom endpoint */

/**
 * 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(WP_REST_Request $request)
{

    /*
    * Accessing request params

    // You can access parameters via direct array access on the object:
    $param = $request['some_param'];

    // Or via the helper method:
    $param = $request->get_param( 'some_param' );

    // You can get the combined, merged set of parameters:
    $parameters = $request->get_params();

    // The individual sets of parameters are also available, if needed:
    $parameters = $request->get_url_params();
    $parameters = $request->get_query_params();
    $parameters = $request->get_body_params();
    $parameters = $request->get_json_params();
    $parameters = $request->get_default_params();

    // Uploads aren't merged in, but can be accessed separately:
    $parameters = $request->get_file_params();
    */

    $posts = get_posts(array(
      'author' => $request['id'],
    ));
   
    if (empty($posts)) {
        return new WP_Error('no_author', 'Invalid author', array( 'status' => 404 ));
    }

    $data = $posts[0]->post_title;
 
    // Create the response object
    $response = new WP_REST_Response($data);
    // Add a custom status code
    $response->set_status(200);
    // Add a custom header
    $response->header('Location', 'http://example.com/');
    
    return rest_ensure_response($response);
}