When working with WordPress, you sometimes end up with unattached media.
Unattached media in WordPress

This could happen for many reasons, usually you sometimes upload files you no longer use or for some other reason ends up unattached.

Now, being unattached does not necessarily mean you do not NEED the file. It could be you have used the media manager to upload your logo for your site, and then inserted the url into an input field in your theme.

The file you uploaded will not be attached to any post/page and will then appear as unattached.

You can either remove the media you do not want from the list via clicking checkboxes (boring).

You could also use some plugin that does this for you (even more boring).

Now here is the fun way (albeit a bit dangerous for your files):

You can also do it via a bit of PHP code. The code will get a list of all unattached media files, loop through it and delete each media.

Please note: This code just flat out deletes all media in WordPress that are unattached. Once the code is done running, the files are gone, so be careful and use at your own risk!


$unattachedmediaargs = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => -1
); 
$unattachedmedia = get_posts($unattachedmediaargs);
if ($unattachedmedia) {
	foreach ($unattachedmedia as $unattached) {
		wp_delete_attachment( $unattached->ID, true );
		// echo "Just deleted media attachment ".$unattached->ID." <br>"; // uncomment this line to see whats going on..
	}
}

Check out the codex page for details on the wp_delete_attachment function.

SEE ALSO:  date_i18n Function Reference and Usage

Note: This code needs the standard WordPress libraries and classes to be loaded to work.

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match