This code creates a custom WordPress REST API endpoint that requires JWT authentication for access, ideal for securing sensitive data exchanges betwee...
Back to Snippets
php
• 34 lines
Custom REST API Endpoint with Authentication
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
/**
* 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 →