What worked for us - appeal to his intelligence and his desire to fit in. Due to likely poor social skills, he probably got into this habit from other kids at school but never got out of it.
We handled it by saying sadly, "Oh really! That is so infantile. Only babies talk like that." We generally played it down. Don't react with shock or horror, boredom is much more effective. Little kids do the potty mouth thing to shock other kids and any adults within earshot. They usually learn fairly quickly that it loses its shock value. But while it HAS shock value, they will use it.
The other thing that always works for us is to inform the child. We explain what a word or phrase means. So when easy child was four and was coming out with a certain nasty four letter word meaning excrement, I told her that was what it mean. She thought about it and then said, "So is that why you use that word when difficult child 1 has a dirty nappy?"
As for the hands down the pants - we still have that at times with difficult child 3. And he's 15. We don't smack (although as a short, sharp reminder it can be useful) but instead we simply said, "For pete's sake, take your hand out of your pants. It won't run away if you let go, you know."
With younger boys who keep playing with "it", my sister used to tell them, "Leave it alone of you will make it sore." (I think that was out of Dr Spock).
We did sit the boys down and tell them that it is simply not polite to have your hand down your trousers like that. People don't like seeing it especially when you will take tat hand out of your pants to reach for food, to open a door, to shake someone's hand and then whatever is on your hands gets shared around - would YOU like to share other people's bottom germs?
and after that we simply kept gently reminding. "Take your hand out of your trousers."
It's an anxiety thing, especially with boys - part of it is the self-skin contact (you see anxious or scared kids hugging themselves or with folded arms) and part of it is the feeling comfortable/nice. I've known of some parents who choose to not inhibit their children and who therefore allow as much of this "self-pleasuring" as the child chooses. Those children then grow up not knowing what is socially acceptable or not. I do think kids need to learn manners. And that is what this boils down to.
So explain the reason for the need for manners and especially THOSE manners, and then keep reminding.
It's about all you can do.
Information and support works best.
Marg