MrPug MrPug - 1 month ago 9
PHP Question

wordpress remove uploaded file

I have created a simple script to upload file in my WordPress plugin using

wp_handle_upload


In database only link to this image is stored. I would like to delete this uploaded file when i delete the post which it is linked to, however using

unlink()


does not work due to link structure which looks like this:
http://localhost/wp-content/uploads/2016/10/image.jpg

Does Anyone know the way to remove "http://[ip]/" from path or any WordPress method to remove uploaded file

I would be grateful for help.

Answer

You can use get_home_path() to get the root directory. Then your code would be:

$url = 'http://localhost/wp-content/uploads/2016/10/image.jpg';
$path = parse_url($url, PHP_URL_PATH); // Remove "http://localhost"
$fullPath = get_home_path() . $path;
unlink($fullPath);
Comments