| 1 |
<?php |
| 2 |
|
| 3 |
namespace EmailKit\Admin\Api; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
|
| 7 |
class DeleteImage |
| 8 |
{ |
| 9 |
|
| 10 |
public $prefix = ''; |
| 11 |
public $param = ''; |
| 12 |
public $request = null; |
| 13 |
|
| 14 |
|
| 15 |
public function __construct() |
| 16 |
{ |
| 17 |
add_action('rest_api_init', function () { |
| 18 |
register_rest_route('emailkit/v1', 'delete-image/(?P<attachment_id>\d+)', array( |
| 19 |
'methods' => \WP_REST_Server::ALLMETHODS, |
| 20 |
'callback' => [$this, 'delete_image'], |
| 21 |
'permission_callback' => '__return_true', |
| 22 |
)); |
| 23 |
}); |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
public function delete_image($request) |
| 28 |
{ |
| 29 |
if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) { |
| 30 |
return [ |
| 31 |
'status' => 'fail', |
| 32 |
'message' => [ esc_html__('Nonce mismatch.', 'emailkit')], |
| 33 |
]; |
| 34 |
} |
| 35 |
|
| 36 |
if (!is_user_logged_in() || !current_user_can('delete_posts')) { |
| 37 |
return [ |
| 38 |
'status' => 'fail', |
| 39 |
'message' => [ esc_html__('Access denied.', 'emailkit') ], |
| 40 |
]; |
| 41 |
} |
| 42 |
|
| 43 |
$attachment_id = $request->get_param('attachment_id'); |
| 44 |
|
| 45 |
if (empty($attachment_id)) { |
| 46 |
return [ |
| 47 |
'status' => 'fail', |
| 48 |
'message' => [ esc_html__( 'Attachment ID is missing.', 'emailkit')], |
| 49 |
]; |
| 50 |
} |
| 51 |
|
| 52 |
$attachment = get_post($attachment_id); |
| 53 |
|
| 54 |
if (!$attachment || $attachment->post_type !== 'attachment') { |
| 55 |
return [ |
| 56 |
'status' => 'fail', |
| 57 |
'message' => [ esc_html__( 'Invalid attachment ID.', 'emailkit')], |
| 58 |
]; |
| 59 |
} |
| 60 |
|
| 61 |
$deleted = wp_delete_attachment($attachment_id, true); |
| 62 |
|
| 63 |
if ($deleted) { |
| 64 |
// Optionally, you can also delete the physical file from the server using the following line: |
| 65 |
// wp_delete_file(get_attached_file($attachment_id)); |
| 66 |
|
| 67 |
return [ |
| 68 |
'status' => 'success', |
| 69 |
'message' => esc_html__( 'Image deleted successfully.', 'emailkit'), |
| 70 |
]; |
| 71 |
} else { |
| 72 |
return [ |
| 73 |
'status' => 'fail', |
| 74 |
'message' => esc_html__( 'Failed to delete image.', 'emailkit'), |
| 75 |
]; |
| 76 |
} |
| 77 |
} |
| 78 |
} |