Forked from anthonycoffey/wp_rest_api_endpoint_example.php
Created
November 25, 2024 17:17
-
-
Save dexit/4efc64e7ba417ca251967eac58fbb643 to your computer and use it in GitHub Desktop.
WordPress REST API Custom Endpoint Example
This file contains hidden or 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