What causes magnetic fields to occur?
Magnetic fields are caused by moving electric charges.
When an electric charge moves it generates a magnetic field. There are several ways in which this can happen.
An electron is a spinning electric charge. This makes each electron a tiny magnet. Electrons form into shells. When a shell is full all of the electrons are paired up with the members of each pair pointing in opposite directions, so the is no net magnetic field. Elements such as Iron, Cobalt and Nickel have unpaired electrons which can be aligned to make a permanent magnet.
When an electric current flows it generates a magnetic field because an electric current is moving charges. Electromagnets are made from strong electric currents flowing through a coil of wire.
Inside the Sun, plasmas of charged particle flow as convection currents. These flows of charged particles cause strong magnetic fields.