Pigs roll in mud primarily in order to regulate their body temperature. This behavior is more commonly referred to as "wallowing."
As well as offering protection from the sun's rays, a coating of moist mud is crucial for keeping pigs cool in warm weather through gradual evaporation. This method is so effective that some have suggested wallowing as the reason for the limited evolutionary development of sweat glands in pigs.
Pigs also wallow in cooler weather, indicating additional motivations such as the removal of parasites, and possibly marking territory with scent. Of course, pigs also genuinely enjoy wallowing for its own sake, showing signs of distress when farmers attempt to curb their behavior with anti-parasite medicines or air-conditioned barns.