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)
wp_TempTable(自定义表)
I want to access this with a custom endpoint... I have searched multiple forums and sites but no luck..
我想用自定义端点访问它……我搜索了多个论坛和网站,但没有运气。
1 个解决方案
#1
2
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
).
是的,这是可能的。这并没有使用Wordpress推荐的控制器模式,而是完成了工作,其中的任务是将传入的json转换成自定义表中的一行(这里称为餐馆)。
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' );
}
) );
} );
#1
2
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
).
是的,这是可能的。这并没有使用Wordpress推荐的控制器模式,而是完成了工作,其中的任务是将传入的json转换成自定义表中的一行(这里称为餐馆)。
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' );
}
) );
} );