Skip to content

Instantly share code, notes, and snippets.

@anthonycoffey
Last active June 30, 2022 11:27
Show Gist options
  • Save anthonycoffey/271dc89dfc7bcb8bd424edf07e5c1d5e to your computer and use it in GitHub Desktop.
Save anthonycoffey/271dc89dfc7bcb8bd424edf07e5c1d5e to your computer and use it in GitHub Desktop.
WordPress REST API Custom Endpoint Example
<?php
/* 1. add function to rest_api_init hook, */
/* 2. then, call register_rest_route() function */
add_action( 'rest_api_init', 'define_endpoint');
function define_endpoint(){
register_rest_route( 'namespace', '/new/route', array(
'methods' => array('POST','GET','UPDATE','DELETE'),
'callback' => 'my_awesome_func'
) );
}
/* 2.a my_awesome_func() callback function */
function my_awesome_func( WP_REST_Request $request ) {
// You can access parameters via direct array access on the object:
$param = $request['some_param'];
// Or via the helper method:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
// The individual sets of parameters are also available, if needed:
$parameters = $request->get_url_params();
$parameters = $request->get_query_params();
$parameters = $request->get_body_params();
$parameters = $request->get_default_params();
// Uploads aren't merged in, but can be accessed separately:
$parameters = $request->get_file_params();
}
?>
@Bonjur
Copy link

Bonjur commented Sep 5, 2020

gj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment