Last active
June 30, 2022 11:27
-
-
Save anthonycoffey/271dc89dfc7bcb8bd424edf07e5c1d5e to your computer and use it in GitHub Desktop.
WordPress REST API Custom Endpoint Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gj