Home > Blockchain >  Delete media file by URL in wordpress
Delete media file by URL in wordpress

Time:10-04

I want to delete media file by URL in Wordpress. like I will paste http://localhost:8080/wordpress/wp-content/uploads/2022/10/image.jpg and media file will be deleted, something like this. I searched a lot, but i could not find any solution.

media is uploading using media library page.

CodePudding user response:

Please try this:

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

CodePudding user response:

It sounds like you want to delete the media file or files associated with a particular item previously uploaded to the media gallery. You can use attachment_url_to_postid() and then wp_delete_attachment() to do this.

$doomed_attachment_id = attachment_url_to_postid( $url );
if ( $doomed_attachment_id ) {
  $result = wp_delete_attachment( $doomed_attachment_id );
  if ( false === $result || null === $result ) {
     /* deletion failure */
  }
}

This is a good way to handle this task because WordPress creates various thumbnail copies of uploaded images and you'll want to get rid of those along with the main image. And, by default, it moves the attachment to the "trash". You can empty the trash later.

Notice that this won't remove the attachment from posts that refer to it. Those posts will contain broken links.

  • Related