# emailkit/1.4.0/includes/Admin/Api/DeleteImage.php

EmailKit – Email Customizer for WooCommerce &amp; WP, version 1.4.0. 78 lines.

- Page: https://pluginprobe.com/plugins/emailkit/1.4.0/code/includes/Admin/Api/DeleteImage.php
- Raw: https://pluginprobe.com/plugins/emailkit/1.4.0/raw/includes/Admin/Api/DeleteImage.php
- Modified: 2023-10-11T06:05:12+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/emailkit/1.4.0/code/includes/Admin/Api/DeleteImage.php#L10-L20`.

```php
<?php 

namespace EmailKit\Admin\Api;

defined('ABSPATH') || exit;

class DeleteImage
{

    public $prefix = '';
    public $param = '';
    public $request = null;


    public function __construct()
    {
        add_action('rest_api_init', function () {
            register_rest_route('emailkit/v1', 'delete-image/(?P<attachment_id>\d+)', array(
                'methods'  => \WP_REST_Server::ALLMETHODS,
                'callback' => [$this, 'delete_image'],
                'permission_callback' => '__return_true',
            ));
        });
    }


    public function delete_image($request)
    {
        if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) {
            return [
                'status'  => 'fail',
                'message' => ['Nonce mismatch.'],
            ];
        }

        if (!is_user_logged_in() || !current_user_can('delete_posts')) {
            return [
                'status'  => 'fail',
                'message' => ['Access denied.'],
            ];
        }

        $attachment_id = $request->get_param('attachment_id');

        if (empty($attachment_id)) {
            return [
                'status'  => 'fail',
                'message' => ['Attachment ID is missing.'],
            ];
        }

        $attachment = get_post($attachment_id);

        if (!$attachment || $attachment->post_type !== 'attachment') {
            return [
                'status'  => 'fail',
                'message' => ['Invalid attachment ID.'],
            ];
        }

        $deleted = wp_delete_attachment($attachment_id, true);

        if ($deleted) {
            // Optionally, you can also delete the physical file from the server using the following line:
            // wp_delete_file(get_attached_file($attachment_id));

            return [
                'status'  => 'success',
                'message' => 'Image deleted successfully.',
            ];
        } else {
            return [
                'status'  => 'fail',
                'message' => 'Failed to delete image.',
            ];
        }
    }
}
```
