Oil and gas companies must permanently plug thousands of Gulf of Mexico wells idle for five years or more under a federal order issued Wednesday.

The mandate could cost well owners billions of dollars, but it could also create jobs for rig workers idled by a federal clampdown on new offshore exploration.

The U.S. Interior Department and its...