Deleting Images With Post In WordPress

wp-badgeThere are some situation in working with WordPress when you want to delete image(s) attached to a post during the post deleting.

Unfortunately, WordPress doesn’t have this logic so attached images will remain on the server’s file system. The only solution is to dive into the code and create a function which will do this automatically.

Note: Make sure that you really want to use this logic. If attached images are used in other posts do not make any changes in the code.

Insert the following code in your theme’s function.php file:

function delete_post_attachments($post_id) {
	global $wpdb;

	$sql = "SELECT ID FROM {$wpdb->posts} ";
	$sql .= " WHERE post_parent = $post_id ";
	$sql .= " AND post_type = 'attachment'";

	$ids = $wpdb->get_col($sql);

	foreach ( $ids as $id ) {
		wp_delete_attachment($id);
	}
}
add_action('delete_post', 'delete_post_attachments');

Share This Post

Recent Articles

Leave a Reply

 
© 2014 CMS Observer. All rights reserved. Site Admin · Entries RSS · Comments RSS