Is it possible to create a Custom endpoint that is connected to the same database but with a custom table? if yes, how?
for example :
wp_TempTable (Custom Table)
I want to access this with a custom endpoint... I have searched multiple forums and sites but no luck..
Yes it is possible. This does not use the Controller pattern recommended by Wordpress but gets the job done, where the job is to convert incoming json into a row in your custom table (here called restaurants
).
function handle_post( WP_REST_Request $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 = implode(", ", $values);
$query = "INSERT INTO `restaurants` ($fields) VALUES ($values)";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'restos/v1', '/post', array(
'methods' => 'POST',
'callback' => 'handle_post',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With