Make sure you’re reaching the correct endpoint by using rest_url()
. When using the REST API and nonces, make sure that the nonce action is set to 'wp_rest'
.
add_action('enqueue_block_editor_assets', function () {
$data = wp_json_encode(array(
'restUrl' => esc_js(rest_url('guide-posts/v1')),
'nonce' => esc_js(wp_create_nonce('wp_rest'))
));
wp_add_inline_script('guide-posts', "var guidePostsAjax = $data");
});
The permission_callback
property is mandatory when registering a REST route. Setting the value to '__return_true'
will indicate that no additional permission checking needs to be done.
function save_guide_locations_rest_route() {
register_rest_route(
'guide-posts/v1',
'/save-locations/(?P<post_id>\d+)',
array(
'methods' => 'POST',
'callback' => 'save_guide_locations',
'permission_callback' => '__return_true'
)
);
}
Remove the nonce validation entirely from the callback function. This will be handled by the REST API since we’re using the wp_nonce
action.
function save_guide_locations( $request ) {
$post_id = $request->get_param( 'post_id' );
// Validate parameter
if ( empty( $post_id ) ) :
return new WP_Error( 'invalid_params', 'Invalid parameters.', array( 'status' => 400 ) );
endif;
// Get the locations data from the request body
$body = $request->get_body();
$locations_data = json_decode( $body, true );
// Check if decoding the JSON was successful
if ( is_null( $locations_data ) ) {
return new WP_Error( 'json_decode_error', 'Failed to decode JSON data.', array( 'status' => 400 ) );
}
// Sanitize and save the locations data
update_post_meta( $post_id, 'guide_locations', $locations_data );
return new WP_REST_Response(array('message' => 'Guide locations saved successfully.'));
}