Make WordPress Core

Opened 11 years ago

Closed 11 years ago

Last modified 7 years ago

#12108 closed feature request (wontfix)

cant delete attachments when deleting a post

Reported by: unsalkorkmaz Owned by:
Milestone: Priority: normal
Severity: normal Version: 2.9.1
Component: General Keywords:
Focuses: Cc:


i want to delete all attached images/videos etc when deleting a post.
it seems there is no solution for it.

simply if a media is attached to a post and post not need anymore, it must be delete too when deleting post.

Change History (5)

#1 @scribu
11 years ago

  • Milestone 2.9.2 deleted
  • Resolution set to wontfix
  • Status changed from new to closed

An attachment can be used in other posts, without being directly attached to them.

Here's some code I use that does what you want:

function delete_post_children($post_id) {
	global $wpdb;

	$ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $post_id AND post_type = 'attachment'");

	foreach ( $ids as $id )
add_action('before_delete_post', 'delete_post_children');
Last edited 7 years ago by SergeyBiryukov (previous) (diff)

#2 @janeforshort
11 years ago

As scribu pointed out, the reason is because media files may be used by other posts as well, which is why they must be deleted in the media library. If we changed it so that deleting a file from a post deleted it altogether from the system, it would break the existing behavior and cause a lot of unintentional deletions. Agree with wontfix.

#3 follow-up: @creativeinfusion
8 years ago

For anyone else who stumbles across this helpful little code snippet and wonders why it isn't working for them, note that you need to use the 'before_delete_post' action since [18012] went live in WordPress version 3.2

This is because the post attachments have already been reassigned to the post parent by the time the 'delete_post' hook is actioned.

#4 in reply to: ↑ 3 @taitxo
7 years ago

Replying to creativeinfusion:
Oh thanks, with the 'before_delete_post' works perfect.

Last edited 7 years ago by taitxo (previous) (diff)

#5 @SergeyBiryukov
7 years ago

Updated the code in comment:1 to use before_delete_post.

Note: See TracTickets for help on using tickets.