The sun spins along its axis, created a magnetic field, at axis direction.
Any planets or moons if carry iron deposit will be induced to become a magnet, have magnetic field.
All planets magnetic field direction must be opposite to the sun's field.
The sun is a giant magnet, earth is a giant compass.
Simple as that, science books are not correct about the cause of earth magnetic field.