wp_delete_attachment doesn’t delete images in wp-content/uploads/

For future reference, if your attachment gets deleted but not your files

There is a filter wp_delete_file, check if this filter is hooked on somewhere, if it returns null your file won’t be deleted but the attachment will

For me it was due to the WPML plugin, they duplicate attachments and then checks that all the attachments are deleted before actually deleting the file

You can either add this action in your theme/plugin, that will delete all translations when using $force_delete in wp_delete_attachment

if ( ! function_exists( 'delete_attachment_translations' ) ) {
    function delete_attachment_translations( $id ) {
        remove_action( 'delete_attachment', 'delete_attachment_translations' );

        $langs = apply_filters( 'wpml_active_languages', [] );

        if ( ! empty( $langs ) ) {
            global $wp_filter;

            //We need to temporarly remove WPML's hook or they will cache the result and not delete the file
            // Sadly they used a filter on a non global class instance, so we cannot access it via regular wp hook
            $hooks = $wp_filter['wp_delete_file']->callbacks[10];
            unset( $wp_filter['wp_delete_file']->callbacks[10] );

            foreach ( $langs as $code => $info ) {
                $post_id = apply_filters( 'wpml_object_id', $id, 'attachment', false, $code );
                if ( $id == $post_id ) {
                    continue;
                }
                wp_delete_attachment( $post_id, true );
            }

            $wp_filter['wp_delete_file']->callbacks[10] = $hooks;
        }

        add_action( 'delete_attachment', 'delete_attachment_translations' );
    }

    add_action( 'delete_attachment', 'delete_attachment_translations' );
}

Or check this option in your WPML settings (But it applies to all posts types, not just attachments)

enter image description here

Leave a Comment

error code: 523