2

I'm trying to add an endpoint with the following:

register_rest_route('namespace/v1','custom-search/(?P<search>[a-zA-Z\s]+)',
        array(
            'methods' => 'GET',
            'callback' => 'gm_custom_search_callback'
        )
    );

It registers the route, but won't recognise when I add a space character i.e. %20 or pass a string with a " " in, I can't see anywhere that would suggest how this should be achieved, am I missing something?

1
  • use placeholders - like - or something more unique in the passed search parameter - just make sure the placeholder is allowed in the endpoint regex - then replace these before passing the value to the callback method.
    – Q Studio
    Commented Nov 7, 2022 at 16:54

1 Answer 1

1

You can do this like this:

function get_custom_search_callback($request) {
    //$parameters = $request->get_params();
    $response = urldecode($request->get_param('search'));

    return rest_ensure_response($response);
}

add_action('rest_api_init', 'add_custom_users_api');
function add_custom_users_api(){
    register_rest_route('namespace/v1',
                        'custom-search/(?P<search>([a-zA-Z]|%20)+)',
                        array(
                            'methods' => 'GET',
                            'callback' => 'get_custom_search_callback'
                        )
                    );
}

Note two things:

  • you have to add %20 to the matched character set
  • you have to urldecode() the search variable value to get rid of the %20 and possibly other urlencoded characters (if you put it in the regex)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.