Creating a REST API Endpoint:
function custom_rest_route() { register_rest_route('custom/v1', '/data/', array( 'methods' => 'GET', 'callback' => 'get_custom_data', )); } add_action('rest_api_init', 'custom_rest_route'); function get_custom_data($data) { // Handle REST API request }
Adding Custom Fields to REST API Response:
function add_custom_fields_to_api() { register_rest_field('post', 'custom_field', array( 'get_callback' => 'get_custom_field_value', 'update_callback' => null, 'schema' => null, )); } add_action('rest_api_init', 'add_custom_fields_to_api'); function get_custom_field_value($object) { return get_post_meta($object['id'], 'custom_field', true); }
Handling Authentication in REST API:
function custom_api_permission_check() {
if (!current_user_can('read')) {
return new WP_Error('rest_forbidden', __('You do not have permissions to access this resource.'), array('status' => 403));
}
return true;
}
add_filter('rest_authentication_errors', 'custom_api_permission_check');
Creating a Custom REST Route:
function custom_rest_route() { register_rest_route('custom/v1', '/data/', array( 'methods' => 'GET', 'callback' => 'get_custom_data', )); } add_action('rest_api_init', 'custom_rest_route'); function get_custom_data($data) { // Handle REST API request }
Securing REST API with API Key:
function verify_api_key($value, $request, $param) { $api_key = 'your_api_key'; if ($value !== $api_key) { return new WP_Error('rest_forbidden', __('Invalid API Key'), array('status' => 401)); } return $value; } add_filter('rest_pre_dispatch', 'verify_api_key', 10, 3);
Adding Custom Fields to REST API Response:
function add_custom_fields_to_api() {
register_rest_field('post', 'custom_field', array(
'get_callback' => 'get_custom_field_value',
'update_callback' => null,
'schema' => null,
));
}
add_action('rest_api_init', 'add_custom_fields_to_api');
function get_custom_field_value($object) {
return get_post_meta($object['id'], 'custom_field', true);
}