add_action('before_delete_post', 'da_auto_delete_post_media', 10); function da_auto_delete_post_media($post_id) { if (get_post_type($post_id) !== 'post') { return; } $media_ids = []; $thumbnail_id = get_post_thumbnail_id($post_id); if ($thumbnail_id) { $media_ids[] = (int) $thumbnail_id; } $attached_media = get_posts([ 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); if (!empty($attached_media)) { $media_ids = array_merge($media_ids, $attached_media); } $post = get_post($post_id); if ($post && !empty($post->post_content)) { $content = $post->post_content; if (preg_match_all('/wp-image-(\d+)/i', $content, $matches)) { $media_ids = array_merge($media_ids, $matches[1]); } if (preg_match_all('/"id":(\d+)(?=[,\}])/', $content, $matches)) { $media_ids = array_merge($media_ids, $matches[1]); } if (preg_match_all('/\[gallery[^\]]*ids="([^"]+)"/i', $content, $matches)) { foreach ($matches[1] as $gallery_ids) { $media_ids = array_merge( $media_ids, array_map('trim', explode(',', $gallery_ids)) ); } } if (preg_match_all('/"ids":\[([^\]]+)\]/i', $content, $matches)) { foreach ($matches[1] as $gallery_ids) { $media_ids = array_merge( $media_ids, array_map( 'trim', explode(',', str_replace(' ', '', $gallery_ids)) ) ); } } } $media_ids = array_unique(array_filter(array_map('intval', $media_ids))); if (empty($media_ids)) { return; } global $wpdb; $id_list = implode(',', $media_ids); $valid_attachments = $wpdb->get_col(" SELECT ID FROM $wpdb->posts WHERE ID IN ($id_list) AND post_type = 'attachment' "); if (!empty($valid_attachments)) { foreach ($valid_attachments as $attachment_id) { wp_delete_attachment((int) $attachment_id, true); } } }