I’m working on building a custom REST API endpoint in WordPress that can handle query parameters instead of path parameters. Right now I have something like /wp-json/v1/items/12345 but I want to change it to use query strings like /wp-json/v1/items?product_id=12345. I need to be able to grab that query parameter value inside my callback function. Here’s what I’ve been trying but it’s not working properly:
// API endpoint handler
function handle_product_request( $request ) {
$product_id = $_GET['product_id'];
return $product_id;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v1', '/items', array(
'methods' => 'GET',
'callback' => 'handle_product_request',
) );
} );
How can I properly set up the route registration and retrieve the query parameter from the URL in the callback function?
You can also use $request->get_query_params() to grab all query parameters as an array. This works great when you’ve got multiple optional parameters and don’t want to define each one in the args array.
function handle_product_request( $request ) {
$params = $request->get_query_params();
$product_id = isset($params['product_id']) ? $params['product_id'] : null;
if (!$product_id) {
return new WP_Error('missing_param', 'Product ID is required', array('status' => 400));
}
return rest_ensure_response($product_id);
}
I use this approach all the time for endpoints that need to handle lots of filter parameters. Just make sure you sanitize the values since you’re skipping the automatic validation from the args definition method.
Your issue arises from using $_GET directly rather than utilizing the WordPress REST API’s parameter handling. You need to define your query parameter while registering the route, allowing you to retrieve it from the $request object.
Consider this modification:
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v1', '/items', array(
'methods' => 'GET',
'callback' => 'handle_product_request',
'args' => array(
'product_id' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param);
}
)
)
) );
} );
function handle_product_request( $request ) {
$product_id = $request->get_param('product_id');
// Your logic here
return rest_ensure_response($product_id);
}
This approach allows WordPress to manage parameter validation and sanitization automatically. The args array enables you to establish validation rules and mark parameters as mandatory, making it a more robust solution than manipulating superglobals directly.
yo, def dont use $_GET. instead, use $request->get_param('product_id') in ur callback. the WP REST API does all that for ya, so no extra setup needed. gl!
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.