For weeks, California trial lawyer Michael Avenatti has seized a starring role in the salacious hush-money scandal unfolding around President Donald Trump.

Inside a courtroom in New York on Wednesday, as cameras swarmed outside, a federal judge decided she had heard enough from Mr. Avenatti, telling him to take his “publicity tour” elsewhere.

“You are entitled to publicity so long as—that is, I can’t stop you, unless you are participating in this matter before me,” U.S. District Judge Kimba Wood told the square-jawed, 47-year-old lawyer.

By the evening, Mr. Avenatti had bowed out of the case involving Michael Cohen, Mr. Trump’s personal lawyer, and the federal investigation into payments Mr. Cohen made to Mr. Avenatti’s client, Stephanie Clifford, the pornographic actress known as Stormy Daniels who says she was paid off to keep quiet about a sexual relationship with Mr. Trump. Mr. Cohen and the White House have said there was no such relationship.

The setback for Mr. Avenatti—who after the hearing appeared on at least four cable-news television shows—represented the latest in a string of blows for the celebrity lawyer, who has become a hero for many eagerly pressing for Mr. Trump’s downfall.