How to remove all unused material slots from all objects?
Via a script.
Removing unused material slots is akin to
Delete all materials that aren&#39;t assigned to a face?
ie remove any slot not associated as a face material, then consolidate.
Similarly to https://blender.stackexchange.com/a/7164/15543 can loop over all selected objects and run the operator for each.
With 2 selected objects each with 3 unused material slots, can call the operator once in python console and it cleans all unused material slots from all selected objects.
&gt;&gt;&gt; bpy.ops.object.material_slot_remove_unused()
Info: Removed 6 slots
{'FINISHED'}

Which has different behaviour to that when using the button in the UI, which as noted only cleans the active object.
Similarly, without   altering  context object or object selection. Example below removes all unused material slots from all objects in scene.
import bpy

context = bpy.context

for ob in context.scene.objects:
    if not ob.material_slots:
        continue
    bpy.ops.object.material_slot_remove_unused(
            {&quot;object&quot; : ob}
            )

or better still, to only run the operator once  Python performance with Blender operators
import bpy

context = bpy.context
scene = context.scene

bpy.ops.object.material_slot_remove_unused(
        {&quot;object&quot; : scene.objects[0],
        &quot;selected_objects&quot; : scene.objects
            }
        )

Note that after running script above there could remain a number of unused materials. (zero user orphans).  These are purged by default on save / reopen. Keep this in mind.
Unused slots vs Unused materials.
IMO big difference between &quot;unused materials&quot; and &quot;unused material slots&quot;  For example if a new material is added to the material slots and never assigned to a face, it is an unused slot, but becomes a used material, since the object becomes a user via the material slots.
This would suggest that Cleaning unused Material Slots in Blender 2.80 Beta was closed under false pretenses.