Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress REST API Custom Endpoint with URL Parameter

I am trying to create a custom endpoint for the WordPress REST API and pass parameters through the URL.

The endpoint currently is:

/wp-json/v1/products/81838240219

What I am trying to achieve is an endpoint that looks like this and being able to retrieve the identifier parameter in the callback.

/wp-json/v1/products?identifier=81838240219

// Custom api endpoint test
function my_awesome_func( $data ) {
  $identifier = get_query_var( 'identifier' );
  return $identifier;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/products=(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );
like image 827
Rob Gelhausen Avatar asked Nov 02 '18 21:11

Rob Gelhausen


People also ask

How do I add URL parameters in WordPress?

There are two ways to use this function; either a single key and value, or an associative array. add_query_arg( array( 'key1' => 'value1', 'key2' => 'value2', ), 'http://example.com' ); Omitting the URL from either use results in the current URL being used (the value of $_SERVER['REQUEST_URI'] ).


3 Answers

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

like image 118
Mo'men Mohamed Avatar answered Nov 02 '22 19:11

Mo'men Mohamed


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;
}
like image 42
Rob Gelhausen Avatar answered Nov 02 '22 21:11

Rob Gelhausen


If you want to pass alphanumeric parameters, use [a-zA-Z0-9-] instead of \d

add_action( 'rest_api_init', function () {
    register_rest_route( 'namespace/v1', '/product/(?P<id>[a-zA-Z0-9-]+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
    ) );
} );
like image 41
geekbro Avatar answered Nov 02 '22 19:11

geekbro