Compass needles line up with magnetic fields. Since Earth is a magnet, a compass will normally line up with Earth’s magnetic field. Because opposite magnetic poles attract, the magnetic north pole of the compass points toward the magnetic south pole of the Earth. (The magnetic south pole of the Earth is located in northern Canada—that is not a misprint. Indeed, the magnetic south pole of the Earth is near the geographic north pole. To make things even more confusing, mapmakers call this the north magnetic pole.)
Electric current passing through a wire creates a magnetic field. In the vertical side of the coil, there are four wires and the current is the same size and moving in the same direction in all of them. Thus the compasses are sensing the magnetic field produced by a current four times larger than if they were surrounded by just one of the wires. This allows the use of a D-cell battery rather than a larger and more expensive battery that would be necessary to produce an equivalent current in a single wire.
The electric current passing through the vertical side of the coil creates a magnetic field that is stronger than Earth’s field (in a region close to the wires). You can visualize the shape of this new field as a set of concentric circles surrounding the vertical coil wires. The closer to the vertical coil wires you are, the stronger the magnetic field. The compass needles align themselves with the total magnetic field at each point, the sum of Earth’s field and that of the wire. Since the magnetic field from the vertical coil wires is significantly larger than that from Earth, each needle ends up pointing essentially in the direction of the magnetic field of the wire.
When you reverse the current, the direction of the magnetic field also reverses, and the needles dutifully follow it.