📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials WordPress Development WordPress REST API

WordPress REST API

5 min read Quiz at the end
WP REST API at /wp-json/wp/v2/ — register custom endpoints with register_rest_route().

WordPress REST API

# Built-in endpoints
GET  /wp-json/wp/v2/posts
GET  /wp-json/wp/v2/posts/42
POST /wp-json/wp/v2/posts  (requires auth)

# Register custom endpoint
add_action('rest_api_init', function() {
    register_rest_route('myapi/v1', '/stats', [
        'methods'             => 'GET',
        'callback'            => 'get_site_stats',
        'permission_callback' => '__return_true', // public
    ]);
    register_rest_route('myapi/v1', '/submit', [
        'methods'             => 'POST',
        'callback'            => 'handle_form',
        'permission_callback' => function() {
            return is_user_logged_in();
        },
        'args' => [
            'email' => ['required'=>true,'sanitize_callback'=>'sanitize_email'],
        ],
    ]);
});

function get_site_stats() {
    return new WP_REST_Response([
        'posts' => wp_count_posts()->publish,
    ], 200);
}
Topic Quiz · 1 questions

Test your understanding before moving on

1. What WordPress function registers a custom REST API endpoint?
💡 register_rest_route() adds a custom endpoint inside the rest_api_init action hook.