rest api – Delete row from table using custom endpoint via API

Question

I would like to delete a row from a table in the database using a custom endpoint via the API. Using an example in the WordPress REST API Handbook, I put together the following code and placed it in my functions.php file:

    function delete_custom_row( $id ) {
    global $wpdb;                           

    return $wpdb->delete(
        'xyz_custom_table',         
        ['id' => $id],                  
        ['%d'],                         
    );
} 

    add_action( 'rest_api_init', function () {
        register_rest_route( 'lic-api/v1', '/deletecustomrow/(?P<id>\d+)', array(
        'methods' => 'POST',
        'callback' => 'delete_custom_row'
        ) );
    } );

I know that I have a row in the table with a column ‘id’ of 3. So when I try to run the code using the endpoint URL of:

/wp-json/lic-api/v1/deletecustomrow/3

The row is not deleted and I get the following error code:

{"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}

Any help would be greatly appreciated.

0
fuxia 2 months 2022-09-29T17:35:12-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse