If you bring a north pole and a south pole together, they will attract. Earth's core contains liquid iron which moves around. Iron is magnetic so the liquid iron causes Earth to have a magnetic field.