php - How do I use WP_REST_Server::CREATABLE to insert into the MySQL db?

I'm having trouble using the WP_REST_Server::CREATABLE, for the WP REST API POST.
I'm trying to insert into the database via POST, but it doesn't work. I was able to get it working via GET but not POST:
<?php
// Register REST API endpoints
class GenerateWP_Custom_REST_API_Endpoints {
/**
* Register the routes for the objects of the controller.
*/
public static function register_endpoints() {
register_rest_route( 'ibl/api/interview', '/greeting', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( 'GenerateWP_Custom_REST_API_Endpoints', 'create_greeting' ),
) );
}
/**
* Add a new greeting
*
* @param WP_REST_Request $request Full data about the request.
* @return List
*/
public static function create_greeting( $request ) {
global $wpdb;
$item = $request->get_json_params();
$fields = array();
$values = array();
foreach($item as $key => $val) {
array_push($fields, preg_replace("/[^A-Za-z0-9]/", '', $key));
array_push($values, $wpdb->prepare('%s', $val));
}
$fields = implode(", ", $fields);
$values = $_GET["greeting"];
$query = "INSERT INTO wp_api (GREETING) VALUES ('$values')";
$list = $wpdb->get_results($query);
return $list;
}
}
add_action( 'rest_api_init', array( 'GenerateWP_Custom_REST_API_Endpoints', 'register_endpoints' ) );
?greeting=ititit
Thank you
Answer
Solution:
Maybe Im i litle late but I think your problem would be fixed adding a nonce.
Wordpress has a security system in REST APIs based in nonces. Maybe is clear for you that you could use it in plugins forms and settings by using the functionwp_create_nonce()
where the first argument is the name of the nonce.
You could Enqueue a JS script and then declare a 'global variable' by usingwp_localize_script()
Then you could declare a nonce as following:
wp_enqueue_script('mm_main_js',plugin_dir_url( __FILE__).'js/main.js',array('jquery'), '1.0', true);
wp_localize_script( 'mm_main_js', 'ajax_requests', array(
'site_url'=>site_url(),
'my_new_nonce'=>wp_create_nonce( 'any_nonce_name' )
));
Ok, the thing is that when you are using the native Worpress REST API and you create a custom route or even you are using the API for creating posts, deleting them, etc., you MUST use the nonce name 'wp_rest'; it is mandatory.
So you must change the previous snipet by:
'my_new_nonce'=>wp_create_nonce( 'wp_rest' )
So let's supose you have the following JS script for posting some information in the custom route.
async deleteRequest(dataId, deleteUrl){
const deleteRequest = await fetch(deleteUrl, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-WP-Nonce": ajax_requests.my_new_nonce, //It is important to send the nonce in this format and on the headers request section
},
body:JSON.stringify({
//Your data
})
})
return deleteRequest;
}
Remember thatajax_requests
is the name of the array created bywp_localize_script
and, as any other object or array in JS you access to any value by codingajax_scripts.variable
, in this case, the nonce created.
Hope it works for you.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.