Many planets have magnetic fields. That of the Earth is believed to be generated through the motion of molten iron in its core creating currents that then generate the terrestrial magnetic field. Jupiter has masses of liquid metallic hydrogen in its outer mantle, creating the largest planetary magnetic field in the solar system. Uranus generates its closer to the surface, meaning strange quadrapole field effects make for a very complicated field – rather than just a north and a south, there’s another two poles lurking in a quadrapole field. In some places like the Moon, the small body freezes over time so that the core can no longer spin around creating its currents and the field shuts down. Mars is intermediate in size between the Earth and the Moon. It ceased to be magnetic roughly half a billion years after formation (meteor or asteroid craters younger than this have no magnetism, suggesting when they churned up the material they hit, they removed any remnant magnetism there and there was nothing to replace it). There are presently two leading theories to how this happened.
The first is a similar one to the Moon. Mars is small, it got cold and the core shut down. Easy enough. The second concerns asteroid impacts. The motions of liquid metals in the core are due to convection – lots of heavy radioactive isotopes are decaying in the core, keeping it warmer than the outer pars of the planet. Hot metal rises to transfer heat from the hot core to the warm mantle. The second theory says that the heat generated by large asteroid impacts during the heavy bombardment period (which is when magnetism shut off in Mars) was enough to warm the outer layer of the planet and shut down convection.
The two theories have their plus points and minus points – magnetism did stop at the heavy bombardment period, but didn’t restart after the mantle cooled again. Earth survived a number of massive impacts, magnetism intact and recently Jupiter survived a cometary impact without noticeable effects on its magnetic field. The core can shut down convection just as part of natural cooling. The two rival viewpoints are explored in an article in ScienceNow.