How does the sun affect the earth's magnetic field?

The sun produces energetic and charged particles and blasts them in all directions (solar winds). These charged particles can get trapped when they are near the earth's magnetic field. With the grace of this magnetic field, we are all shielded from being irreversible harmed. See the picture in the related link for a visualization of how the magnetic field gets distorted by solar winds.

============================