Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/c8b6ee27bebbdbf0156d819001c61bf1 to your computer and use it in GitHub Desktop.
Save mishterk/c8b6ee27bebbdbf0156d819001c61bf1 to your computer and use it in GitHub Desktop.
WordPress REST API recipes
<?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