Back to Snippets

Custom REST API Endpoint with Authentication

PHP REST API April 6, 2026

Register a custom REST API endpoint with permission checks, parameter validation, sanitization, and proper WP_REST_Response.

Snippet Stats

Lines 34
Characters 1,178
Read 1 min
php • 34 lines
/**
 * Register a custom REST API endpoint.
 */
add_action( 'rest_api_init', function() {
    register_rest_route( 'mytheme/v1', '/projects', array(
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'mytheme_get_projects',
        'permission_callback' => function() {
            return current_user_can( 'edit_posts' );
        },
        'args' => array(
            'per_page' => array(
                'default'           => 10,
                'sanitize_callback' => 'absint',
                'validate_callback' => function( $value ) {
                    return is_numeric( $value ) && $value > 0 && $value get_param( 'per_page' );

    $query = new WP_Query( array(
        'post_type'      => 'portfolio',
        'posts_per_page' => $per_page,
        'no_found_rows'  => true,
    ) );

    $projects = array_map( function( $post ) {
        return array(
            'id'      => $post->ID,
            'title'   => $post->post_title,
            'excerpt' => get_the_excerpt( $post ),
            'url'     => get_permalink( $post ),
        );
    }, $query->posts );

    return new WP_REST_Response( $projects, 200 );
}

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
PHP
This code creates a custom WordPress REST API endpoint that requires JWT authentication for access, ideal for securing sensitive data exchanges betwee...

WordPress Custom REST API Endpoint With JWT Authentication

PHP
Custom REST API search endpoint with input validation and sanitization. Returns snippet titles, excerpts, and URLs for AJAX search.

Custom REST API Endpoint: Search Snippets