There is a free application on the Android Market that handles this task for you. WiFi Automatic auto-enables Wi-Fi when your device is plugged in for charging via USB and disables it whenever it is disconnected. The app has been around for a while now. This review is for those who are still unaware of the tool and are fond of automizing their devices.
The interface of the application is extremely simple. Tapping the toggle button (top) enables or disables the background service that checks whether the phone is plugged in for charge via USB.
Tapping the settings button allows you to configure service settings. You can even enable a Notification sound to alert you whenever Wi-Fi is enabled/disabled as a result of USB cable connection/disconnection.
A particularly interesting feature is the Previous state before charger connection option in the Additional options menu, which when selected, sets the application to retain the pre-connection Wi-Fi status once the device is disconnected. That is, the application remembers whatever the status of the Wi-Fi on your device was before it was plugged in and restores it to that status when it is plugged out.
You can download WiFi Automatic from the Market for free via the link below or by scanning the provided QR code.