Back to Snippets

Custom REST API Endpoint: Search Snippets

PHP REST API April 6, 2026

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

Snippet Stats

Lines 39
Characters 1,337
Read 2 mins
php • 39 lines
/**
 * Register a search endpoint for snippets.
 */
add_action( 'rest_api_init', function(): void {
    register_rest_route( 'ifcodif/v1', '/search', array(
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'ifci_rest_search_snippets',
        'permission_callback' => '__return_true',
        'args'                => array(
            'q' => array(
                'required'          => true,
                'sanitize_callback' => 'sanitize_text_field',
                'validate_callback' => function( $value ) {
                    return is_string( $value ) && strlen( $value ) >= 2;
                },
            ),
        ),
    ) );
} );

function ifci_rest_search_snippets( WP_REST_Request $request ): WP_REST_Response {
    $query = new WP_Query( array(
        'post_type'      => 'ifci_snippet',
        'posts_per_page' => 10,
        's'              => $request->get_param( 'q' ),
        'no_found_rows'  => true,
    ) );

    $results = array_map( function( WP_Post $post ): array {
        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( $results, 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
Register a custom REST API endpoint with permission checks, parameter validation, sanitization, and proper WP_REST_Response.

Custom REST API Endpoint with Authentication