According to legends, Goddess Parvati created Ganesha with the mud of her body and asked him to guard the house while she takes a bath.
She tells Ganesha not to let anyone in.
When Lord Shiva returned home, Ganesha refuses to let him get inside the house. Enraged, Lord Shiva cuts off his head.
On learning what happened, Goddess Parvati was overcome with grief. In order to console her, Shiva sends his servants and asks them to bring the head of any creature they find first.
The first animal they found was an elephant and that is how Lord Ganesha got an elephants head.