The end of the level "Death, Baby" is broken into 3 sections, the doors to which are accessed by selecting different colored statues that match the colors of the doors. Just be sure to select the purple statue before selecting the orange statue, since the orange statue and door lead to the section where the pirate hat is automatically obtained.
If you use the purple statue and door after having already completed the section accessed with the orange statue, your pirate hat that you obtained during the orange section will be replaced with a different hat. It doesn't matter what order you select the green statue in. As long as you make sure to complete the orange section after the purple section, the level will end with you still wearing the pirate hat.