Delete an image in PHP (WordPress)

I have this code which uploads an image from admin and it works well.

add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
    register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
function validate_setting($theme_options) {
         $keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {  
         // if a files was upload 
         if ($image['size']) {  
         // if it is an image  
         if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) {       $override = array('test_form' => false);    
         $options = get_option('theme_options');  echo "<img src='{$options['logo']}' />";
         // save the file, and store an array, containing its location in $file 
         $file = wp_handle_upload( $image, $override );       $theme_options[$keys[$i]] = $file['url'];     } else {   
         // Not an image.     
         $options = get_option('theme_options');       $theme_options[$keys[$i]] = $options[$logo];   
         // Die and let the user know that they made a mistake.   
         wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.');     }   }   // Else, the user didn't upload a file.  
         // Retain the image that's already on file.   
         else {     $options = get_option('theme_options');     $theme_options[$keys[$i]] = $options[$keys[$i]];   }   $i++; }
         return $theme_options;

and now I want the function to delete the current image.

     function delete_file($theme_options) {
     if (array_key_exists('delete_file', $_FILES)) {
      $image = $_FILES['delete_file'];
      if (file_exists($image)) {
        echo 'File '.$image.' has been deleted';
      } else {
        echo 'Could not delete '.$image.', file does not exist';

I added the button in admin but is doing.. nothing.
I’m building a TemplateOptions in WordPress and now I’m trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field “delete” to work.


Read more here: Delete an image in PHP (WordPress)

Leave a Reply

Your email address will not be published. Required fields are marked *