Origin of idiom "wearing the < role > hat?"
There's a related discussion over at The Phrase Finder:
I think it comes from a time (not long ago) when everyone wore hats, and many of those hats were specific to a given trade, official position or function. So someone who had several roles would have several hats and would wear the appropriate one for the occasion. [...] "which hat will you be wearing?" would mean "in which capacity will you be attending?"
As you can see, it's just speculation without citing any sources, so I have looked it up in the American Heritage Dictionary of Idioms, and here's what it has to say:
wear another hat Also, wear a different hat or two hats; wear more than one hat. Function in a different or more than one capacity or position, as in I'm wearing another hat today; yesterday I was a housewife, today I'm an attorney, or I wear two hats—are you asking me as a member of the city council or as a storeowner? This metaphoric expression alludes to headgear worn for different occupations. [Mid-1900s]
So it's indeed a metaphor, and a relatively young one.
It may or may not be the original source of this usage of the term, but in a 1965 article on administration, Scientology founder L. Ron Hubbard wrote:
HAT: Slang for the title and work of a post in an org. Taken from the fact that in many professions such as railroading the type of hat worn is the badge for the job.
The article is a policy letter (article on the administration methods to be applied by Scientology Churches) from 1 July 1965—the third such issue on that particular day. Its title is "Hats, The Reason For."
The word "hat" with this meaning is used liberally throughout Scientology materials on administration, many of which date from the early 1960s.
There is an earlier article (policy letter) from 28 February 1957, titled simply "Hats," which seems to be one of the earliest usages of this particular definition by Mr. Hubbard.
It would not surprise me at all if that were the original source of this definition, though I have no evidence either way on that. (Proving a negative is difficult, but this at least aligns with the approximate dates mentioned in other answers.)