Make WordPress Core

Opened 14 years ago

Closed 14 years ago

Last modified 10 years ago

#12108 closed feature request (wontfix)

cant delete attachments when deleting a post

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

Description

Hi.
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
14 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 )
		wp_delete_attachment($id);
}
add_action('delete_post', 'delete_post_children');
Version 0, edited 14 years ago by scribu (next)

#2 @janeforshort
14 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
11 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
10 years ago

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

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

#5 @SergeyBiryukov
10 years ago

Updated the code in comment:1 to use before_delete_post.

Note: See TracTickets for help on using tickets.