Created
June 6, 2018 06:51
-
-
Save mishterk/c8b6ee27bebbdbf0156d819001c61bf1 to your computer and use it in GitHub Desktop.
WordPress REST API recipes
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 | |
/** | |
* Really simple GET request | |
*/ | |
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) { | |
register_rest_route( '/custom-namespace/v1', '/no-param', [ | |
'methods' => 'GET', | |
'callback' => function ( WP_REST_Request $request ) { | |
if ( $throw_error = false ) { | |
return new WP_Error( 'some-error-code', 'There was an error', [ | |
'heres' => 'some', | |
'error' => 'data' | |
] ); | |
} else { | |
return new WP_REST_Response( [ | |
'here' => 'is', | |
'some' => 'data' | |
], 200 ); | |
} | |
} | |
] ); | |
} ); | |
/** | |
* Really simple GET request that accepts an integer as a parameter/arg | |
*/ | |
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) { | |
register_rest_route( '/custom-namespace/v1', '/numeric-param/(?P<numeric_param>[\d]+)', [ | |
'args' => [ | |
'numeric_param' => [ | |
'description' => __( 'Some numberic parameter' ), | |
'type' => 'integer' | |
], | |
], | |
[ | |
'methods' => 'GET', | |
'callback' => function ( WP_REST_Request $request ) { | |
if ( $throw_error = false ) { | |
return new WP_Error( 'some-error-code', 'There was an error', [ | |
'heres' => 'some', | |
'error' => 'data' | |
] ); | |
} else { | |
return new WP_REST_Response( [ | |
'here' => 'is', | |
'some' => 'data', | |
'using' => 'provided', | |
'arg' => $request->get_param( 'numeric_param' ) | |
], 200 ); | |
} | |
} | |
] | |
] ); | |
} ); | |
/** | |
* Really simple GET request that accepts a string as a parameter/arg | |
*/ | |
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) { | |
register_rest_route( '/custom-namespace/v1', '/string-param/(?P<string_param>[a-zA-Z0-9_-]+)', [ | |
'args' => [ | |
'string_param' => [ | |
'description' => __( 'Some string arg' ), | |
'type' => 'string' | |
], | |
], | |
[ | |
'methods' => 'GET', | |
'callback' => function ( WP_REST_Request $request ) { | |
if ( $throw_error = false ) { | |
return new WP_Error( 'some-error-code', 'There was an error', [ | |
'heres' => 'some', | |
'error' => 'data' | |
] ); | |
} else { | |
return new WP_REST_Response( [ | |
'here' => 'is', | |
'some' => 'data', | |
'using' => 'provided', | |
'arg' => $request->get_param( 'string_param' ) | |
], 200 ); | |
} | |
} | |
] | |
] ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment