I am allowing user’s to upload their images, so to show their uploaded images i am using<?php echo $options_images['image_bg'];?>
which outputs this:http://www.mydomain.com/myfolder/wp-content/uploads/2013/05/deleteme.png
. So now my image is displayed properly.
Now i want to allow my users to delete that image and this is the where I failed miserably.
The problem: In order to delete that image I know I must use unlink()
function but to actually use it i need to retrieve dynamically its directory only ('wp-content/uploads/2013/05/deleteme.png';
) part (Correct me if I am wrong).
So somehow (I think at least) i need to read $options_images['image_bg']
, and then get rid of http://www.mydomain.com/
but that path also can be anything
for example:http://www.mydomain.com/wp-content/uploads
or http://www.mydomain.com/somefolder/someotherfolder/wp-content/uploads
so I need to retrieve dynamically only somefolder/wp-content/uploads/2013/05/deleteme.png
part but I have no idea how to achieve that! Currently I can delete my image but only when i am using my path hard coded like this:
<!--allow users to delete image
HARDCODED so it is a no go:(
-->
<?php $filename = 'wp-content/uploads/2013/05/deleteme.png';
if(file_exists('wp-content/uploads/2013/05/deleteme.png')){
unlink('wp-content/uploads/2013/05/deleteme.png');
}
?>
I tried this also but it is not working
<?php $filename = $options_images['image_bg'];
if(file_exists($filename)){
unlink($filename);
}
?>
I am using this function inside my Theme options for image upload:
//Validate our settings here
function validate_setting($plugin_options){
//echo '<pre>'; print_r($_FILES); echo '</pre>';
$keys = array_keys($_FILES);
$i = 0;
foreach ($_FILES as $image) {
//If file was uploaded...
if($image['size']){
//Is it an image?
if(preg_match('/(jpg|jpeg|png|gif)$/i',$image['type'])){
$override = array('test_form' => false);
$file = wp_handle_upload($image,$override);
$plugin_options[$keys[$i]] = $file['url'];
}
else{
wp_die('No image found');
}
}
else{
$options = get_option('sandbox_theme_social_options');
$plugin_options[$keys[$i]] = $options[$keys[$i]];
}
$i++;
}
return $plugin_options;
}
But obviously this is a no go because image names can be anything and http://www.mydomain.com/
can be changed to anything (http://www.mydomain.com/folder/other_folder/and_other_folder
)
Can anybody help me with this?
Use wp_delete_attachment
Because you guy’s helped me a lot with your answers this is how I did it if someone is interested:
Obviously i will need to check if the user chooses to delete image or not but it shouldn’t be a problem. THX guys!!
I was going through the same problem as you are now.
Then I learned to convert url to path and delete any image or file from server.
I am using this function for converting url to path and working fine for me.