WordPress REST API Custom Endpoint with URL Parameter WordPress REST API Custom Endpoint with URL Parameter wordpress wordpress

WordPress REST API Custom Endpoint with URL Parameter


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' );}

The process is very simple but requires you to read this documentation


I modified the provided answer a little to get my desired endpoint:

/wp-json/api/v1/product?identifier=81838240219

add_action( 'rest_api_init', function () {register_rest_route( 'api/v1', '/product/', array(      'methods' => 'GET',      'callback' => 'ea_get_product_data',    ) );} );function ea_get_product_data( $data ) {    $identifier = $data->get_param( 'identifier' );    return $identifier;}