A judge blocked President Trump’s anti-sanctuary city executive order Tuesday, accusing the White House of wrongly trying to threaten the cities and saying Congress, not the president, gets to decide what strings to attach to federal funds.

The ruling was still a partial victory for the president though, with the judge saying the administration can withhold funds in cases where the law already gives him permission.

That clears the path for Attorney General Jeff Sessions to strip sanctuary cities of hundreds of millions of dollars doled out each year across three Justice Department grant programs.

Still, the nationwide injunction by U.S. District Judge William H. Orrick is the latest legal spanking for Mr. Trump, who has now seen three executive orders — all of them dealing with immigration and homeland security policy — halted by the courts.

“Once again, the courts have spoken to defend tolerance, diversity and inclusion from the illegal threats of the Trump administration. Once again, Trump has overreached and lost,” the American Civil Liberties Union said after the ruling.

Mr. Trump issued his sanctuary city policy in a Jan. 25 executive order, saying he wanted his attorney general and homeland security secretary to come up with an official definition of sanctuary cities, then try to strip them of perhaps tens of billions of dollars the federal government pays to them each year.

Analysts said everything from Medicaid money to school funds could have been on the chopping block.

Judge Orrick, however, said Congress has the power of the purse and gets to decide what strings are attached to federal money. He sided with two California counties, San Francisco and Santa Clara, that had sued to stop the executive order.

“The counties have a strong interest in avoiding unconstitutional federal enforcement and the significant budget uncertainty that has resulted from the order’s broad and threatening language,” Judge Orrick wrote.

The Justice Department portrayed the ruling as little more than a symbolic setback, saying it had already limited the punishment to the three programs the judge said can be cut off under existing law.

“Accordingly, the department will continue to enforce existing grant conditions and will continue to enforce 8 U.S.C. 1373,” Justice Department spokesman Ian Prior said. “Further, the order does not purport to enjoin the Department’s independent legal authority to enforce the requirements of federal law applicable to communities that violate federal immigration law or federal grant conditions.”

San Francisco, though, said the injunction was an embarrassment to Mr. Trump.

“I hope this president learns from his litany of mistakes. His first 100 days have been a disaster. I hope, for all of our sakes, that he can turn it around,” said Dennis Herrera, San Francisco’s city attorney.

Mr. Trump made sanctuary cities a centerpiece of his presidential campaign, and made San Francisco a particular target after the 2015 killing of Kate Steinle. The man who’s admitted to shooting her is an illegal immigrant who had been protected from deportation by San Francisco’s sanctuary policy.

In office, however, Mr. Trump has struggled to make good on his promise to crack down on illegal immigration.

The Department of Homeland Security was forced to halt its weekly name-and-shame list of sanctuaries after it made too many errors, and the administration is still struggling to come up with an official definition of what a sanctuary is.

Meanwhile, a rash of new cities and counties has passed policies protecting illegal immigrants, saying they are determined to thwart Mr. Trump.

Not all sanctuary policies are the same. Some jurisdictions prohibit all communication with U.S. Immigration and Customs Enforcement, while others will share information with ICE but restrict cooperation with the agency’s detainer requests, which often ask local authorities to hold illegal immigrants beyond their regular release time.

Several courts have ruled that prolonged detainers violate the Constitution.

A delegation of mayors met Tuesday with Mr. Sessions, and said they made some headway in trying to hash out what policies the Trump administration deems in violation of the law.

“We heard a narrowing of what might be a sanctuary city,” said Steve Adler, mayor of Austin, Texas.

But local officials said they still want more detail on how the administration expects them to treat detainer requests.

“Do we have legal authority to hold people on detainers?” said Chief Tom Manger, head of the Major Cities Chiefs Association and head of the Montgomery County, Maryland, police department.

Judge Orrick said that while Mr. Trump can’t go beyond the laws written by Congress, he can enforce existing laws — including U.S. Code Section 1373. That law prohibits jurisdictions from enacting policies that restrict communications with Homeland Security “regarding the citizenship or immigration status, lawful or unlawful, of any individual.”

The three programs are the Byrne Justice Assistance Grants, the COPS program and the State Criminal Alien Assistance Program, which pays local prisons and jails to hold illegal immigrants.

Mr. Sessions last week sent letters to nine jurisdictions demanding they explain their sanctuary policies and try to square them with a federal law that requires them to share information with federal immigration agents.

The state of California was one of the jurisdictions. Neither San Francisco nor Santa Clara was on the target list.

Local officials who met with Mr. Sessions on Tuesday doubted the law will snare many jurisdictions.

Chief Manger said very few local law enforcement agencies are outright blocking communications with ICE.

“If that’s the definition of a sanctuary city, I don’t think there are any sanctuary cities in the U.S.,” said Jorge Elorza, mayor of Providence, Rhode Island.

But the Justice Department inspector general last year identified a number of jurisdictions, including San Francisco, which it said had policies that likely did run afoul of Section 1373.

Judge Orrick’s 49-page order is the latest to use Mr. Trump’s own words against him.

The judge wrote that the government acknowledged “the order cannot do more constitutionally than enforce existing law,” but that the language in the order attempted to apply the authority to restrict federal funds to all federal grants, not just the three mentioned by the Justice Department.

“If there was doubt about the scope of the order, the president and attorney general have erased it with their public comments,” Judge Orrick wrote. “The President has called it ‘a weapon’ to use against jurisdictions that disagree with his preferred policies of immigration enforcement.”

Mr. Trump’s words about a “Muslim ban” have also come back to bite him on his extreme vetting policy, with several federal judges saying that no matter what his executive order looks like on its face, his comments have tainted the process and made the order likely unconstitutional.