WordPress.org

Make WordPress Core

Opened 5 years ago

Closed 5 years ago

Last modified 12 months 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:

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)

comment:1 @scribu5 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('before_delete_post', 'delete_post_children');
Last edited 12 months ago by SergeyBiryukov (previous) (diff)

comment:2 @janeforshort5 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.

comment:3 follow-up: @creativeinfusion21 months 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.

comment:4 in reply to: ↑ 3 @taitxo12 months ago

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

Last edited 12 months ago by taitxo (previous) (diff)

comment:5 @SergeyBiryukov12 months ago

Updated the code in comment:1 to use before_delete_post.

Note: See TracTickets for help on using tickets.