I'm totally new to wordpress/php I'm trying to use Angular with the rest API to do basic CRUID on custom table professor_schedule
.
To query the table everything works. This is what I have.
PHP
// get all schedules
function getAllProfessorSchedule( $data ) {
global $wpdb;
$query = "SELECT nom FROM `professor_schedule`";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'professor-schedule/v2', '/all', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'getAllProfessorSchedule'
));
});
JS
function getAllSchedules(){
$http({
method: 'GET',
url : 'http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/all'
}).then(function (response) {
console.log(response.data)
$scope.data = response.data
}, function (response) {
console.error("error !! ", response)
});
}
Below is the code to insert data into the DB. The server respond with a 403 (Forbidden)
I'm logged in with an administrator account I have tried with the Basic Auth plugin but I always get the 403 error. I'm struggling for hours now. I would get any advices. Thanks
PHP
function addNewSchedule( WP_REST_Request $request ) {
// $args = array(
// 'headers' => array(
// 'Authorization' => 'Basic ' . base64_encode( 'user:password' ),
// ),
// );
// wp_remote_request( $url, $args );
global $wpdb;
$item = $request->get_json_params();
$fields = array();
$values = array();
foreach($item as $key => $val) {
array_push($fields, $key);
array_push($values, $val);
}
$fields = implode(", ",$fields);
$values = implode("','",$values);
$query = "INSERT INTO `professor_schedule` (".$fields.") VALUES ('".$values."')";
//$query = "INSERT INTO `professor_schedule` ('Nom') VALUES ('test')";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'professor-schedule/v2', '/add', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'addNewSchedule',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
JS
$scope.addNewSchedule = function(){
$http({
method : "POST",
url : "http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/add",
params:
{
nom : $scope.scheduleModel.nom
}
}).then(function(){
getAllSchedules();
});
}
I had the same issue WordPress endpoints. You can try disabling mod_security
on your server or making an exception for mod_security
for the REST endpoints. Also you can try WordPress on your local server and confirm issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.