There are a number of stories about how Ganesh (or Ganesha) ended up with the head of an elephant, although most involve him getting decapitated. The most well-known story comes from the Shiva Purana.
In this version, the goddess Parvati wanted to take a bath and set Nandi, the bull of Shiva, to guard the door. However, because Nandi was loyal to her husband Shiva first, the bull did not stop Shiva when he tried to enter, disturbing Parvati. Enraged, the goddess used either turmeric or sandalwood to create a boy, Ganesh, to guard the door.
Parvati took another bath, and again, Shiva tried to enter. Ganesh tried to stop him, but this only angered Shiva who did not realize that Ganesh was Parvati's son. He beheaded Ganesh and passed through the door.
However, Parvati was now furious and threatened to destroy all of creation if her son was not brought back to life. To appease her, Shiva sent out his minions, the ganas, to bring back the head of the first living being they found. This turned out to be an elephant, and so Ganesh was revived with an elephant head. He was later made into the head of Shiva's followers, which is why his name means "commander of the ganas."