WordPress REST API Custom Endpoint with URL Parameter

Picture of Amitpal Singh
Amitpal Singh
May 9, 2022

First you need to pass in the namespace to register_rest_route

Like this

add_action( 'rest_api_init', function () {
    register_rest_route( 'namespace/v1', '/product/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
    ) );
} ); 

Your name space namespace/v1 and your route is /product/{id} like this /namespace/v1/product/81838240219

and now you can use the route inside your function like this

function my_awesome_func( $data ) {
    $product_ID = $data['id'];
} 

If you need to add options for ex. /namespace/v1/product/81838240219?name=Rob

and use it inside the function like this

function my_awesome_func( $data ) {
    $product_ID = $data['id'];
    $name = $data->get_param( 'name' );
} 

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.