2

I am creating a custom route using WP API this way:

 register_rest_route( 'service/v1', 'shopping', array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'my_awesome_function',
        ));

I am writing the following function:

function my_awesome_function($request_data) {
    $parameters = $request_data->get_params();
    if( !isset( $parameters['product'] ) || empty($parameters['product']) ){
        return array( 'error' => 'No product provided' );
    }else{
        $product = $parameters['product'];\

       return array( 'Product' => $product );

    }
}

This works perfectly fine using this structure www.example.com/wp-json/service/v1/shopping?product=perfume

However I want it to work in a RESTful way using the URL: www.example.com/wp-json/service/v1/shopping/perfume

Should I change the way I am registering the route or this is not possible and needs to be done through URL rewrite in .htaccess?

1
  • You may have more help for that on the site for WordPress development questions : wordpress.stackexchange.com Commented Feb 9, 2018 at 18:05

1 Answer 1

1

You can use something like:

register_rest_route( 'service/v1', 'shopping/(?P<id>[\d]+)', array(
    'methods'  => WP_REST_Server::READABLE,
    'callback' => 'my_awesome_function',
));

The regex at the end of the path will capture a single or more digits and set it as an "id" parameter which you can then use to get the relevant product

You can use something like: (?P<slug>[a-zA-Z0-9-]+) to capture a "slug" with uppercase/lowercase letters, numbers and/or dashes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.