带有 URL 参数的 WordPress REST API 自定义端点

WordPress REST API Custom Endpoint with URL Parameter

我正在尝试为 WordPress REST 创建自定义端点 API 并通过 URL.

传递参数

当前端点是:

/wp-json/v1/products/81838240219

我想要实现的是一个看起来像这样的端点,并且能够在回调中检索标识符参数。

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

首先需要将namespace传入register_rest_route

像这样

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

你的名字spacenamespace/v1你的路线是/product/{id}这样的 /namespace/v1/product/81838240219

现在您可以像这样在函数中使用路由

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

如果您需要为 ex 添加选项。 /namespace/v1/product/81838240219?name=Rob

并像这样在函数内部使用它

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

过程非常简单,但需要您阅读本文documentation

我稍微修改了提供的答案以获得我想要的端点:

/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;
}

如果要传递字母数字参数,请使用 [a-zA-Z0-9-] 而不是 \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',
    ) );
} );