The massacre at a gay nightclub in Orlando—the worst act of terrorism on American soil since the attacks of 9/11—had barely ended when the debate over its significance began. As usual, the political class divided into competing camps, with liberals predictably claiming that the real issue is gun control and conservatives just as predictably claiming that the real issue is radical Islam. There wasn’t even agreement over whether this was a hate crime or an act of terrorism. (Why couldn’t it be both?)

Faced with the cacophony of competing sound bites, it is tempting to throw one’s hands up in despair and simply bemoan the debased state of political discourse. But we don’t have that luxury, because terrorism remains a real and growing danger. So how should we combat it? By adopting the best ideas from the left and the right on how to improve security at home and by going after terrorists abroad. In dealing with such a complex threat, no part of the political spectrum has a monopoly on the truth.

Start with domestic security. The state of our homeland defenses has improved since 9/11, thanks to greater awareness of the terrorist threat, greater resources devoted to stopping it and greater cooperation among law enforcement and intelligence agencies. But it is hard to stop a violent fanatic from walking into a nightclub and opening fire—and always will be.

The fact that there are more than 300 million firearms in private hands in the U.S. compounds the danger, because it means that anyone with a grudge can acquire the means to commit mass murder. Terrorists are aware of this vulnerability and seek to exploit it. As the American-born al Qaeda spokesman Adam Gadahn said in a 2011 video, “America is absolutely awash with easily obtainable firearms. You can go down to a gun show at the local convention center and come away with a fully automatic assault rifle without a background check and most likely without having to show an identification card. So what are you waiting for?” (You can’t buy a fully automatic weapon, but otherwise he was correct.)

Omar Mateen did not wait. Possibly inspired by a recent message from Islamic State urging its followers to turn Ramadan into “a month of suffering,” he marched into the Pulse nightclub and opened fire. The fact that he was able to work as a licensed security guard and to legally purchase firearms, despite having been investigated twice by the FBI for potential terrorist ties, suggests a fundamental breakdown in our safeguards.

There is no reason why the American public should be able to purchase military-style semiautomatic weapons such as the AR-15, which has become a favorite of mass shooters. As retired Gen. Stanley McChrystal, one of the leaders of a new veterans’ group for gun control, notes, the purpose of the AR-15 is to kill a great many people as quickly as possible. It is also important to ban high-capacity magazines, which allow a killer to keep killing without reloading. Mateen used a Sig Sauer MCX semiautomatic rifle (similar to the AR-15) with a 30-round magazine.

Even if bans on assault weapons and high capacity magazines aren’t politically possible, Congress should, at a minimum, prevent suspects on terrorism watch lists from purchasing firearms legally—something that they were able to do 223 times in 2015, according to the Government Accountability Office. (Only one transaction in 10 was denied.)

But we should have no illusions that gun control by itself will keep us safe. France and Norway, among other countries with strict gun laws, have suffered attacks even more deadly than the one in Orlando.

So, too, hardening potential “soft targets” is necessary but insufficient. By all means, let’s follow the example of Israel and have more security guards and more metal detectors at the entrances of clubs and malls. But a determined attacker will still get through. The nightclub in Orlando had an armed, off-duty police officer at the entrance; he fired at Mateen but was unable to stop him from getting inside.

The best bet to stop terrorists is to uncover their intentions in advance. The FBI has done just that since 2001 by sending undercover agents and informants to pose as would-be terrorists to prosecute suspects intent on turning violent. Such investigations have resulted in charges against nearly 90 Americans but have also sparked controversy, with civil libertarians accusing the FBI of entrapping innocent people. Now, of course, the FBI is accused of the opposite sin—of not being aggressive enough in uncovering Mateen’s radical views. Either way, the bureau will be criticized. Better to err on the side of public safety.

Other controversial counterterrorism programs need to be continued or revived. After 9/11, the New York Police Department sent plainclothes detectives into mosques and Muslim neighborhoods to try to spot early signs of radicalization. Mayor Bill de Blasio and Police Commissioner William Bratton ended this program in 2014 amid intense criticism from civil-liberties groups.

The National Security Agency, meanwhile, has been forced to curtail its intelligence-gathering following the revelations of Edward Snowden. The USA Freedom Act, passed by Congress in 2015, ended the NSA’s collection of “metadata,” which reveals the phone numbers that everyone dials but not the content of calls. This wasn’t a crippling change, but it suggests that we are returning to a pre-9/11 mind-set. The shootings in San Bernardino and Orlando, the Boston Marathon bombing and other attacks by homegrown terrorists should remind us of the dangers of complacency in the face of a threat that continues to metastasize.

Though electronic monitoring is important, the most effective way to identify potential terrorists is through old-fashioned human-intelligence gathering—that is, by talking to friends and family who might detect early signs of radicalism, as some did in Mateen’s case. That, in turn, depends on cultivating good relations with the American Muslim community, where a very small number of potential terrorists lurk amid a great mass of law-abiding people.

Donald Trump’s crude Muslim-bashing makes that objective harder to achieve. After the Orlando shooting, the presumptive Republican presidential nominee suggested, without any evidence, that the American Muslim community was complicit in the attack and must have known of it in advance. He also renewed his call to ban all foreign Muslims—a radical move that wouldn’t have stopped the American-born Mateen and would in any case be almost impossible to enforce. (How would border agents know if a visitor is Muslim or not?)

Mr. Trump is sending Muslims a message that they are less than wholly American. He is also emulating the worst excesses of the McCarthy era by intimating that there are terrorist sympathizers in high places—even, absurdly, in the Oval Office itself.

The populist billionaire is playing with fire. Part of the reason there has been less terrorism in the U.S. than in Europe is that we have done a better job of assimilating Muslims. It would be a costly tragedy if that achievement were to be undone.

Mr. Trump’s other demand is for President Barack Obama to refer to “radical Islamic terrorism” in his speeches or else resign on the spot. Mr. Trump seems to imagine that “radical Islamic terrorism” is a magical incantation—that simply by reciting this phrase we can make the threat go away.

The president may have played into Mr. Trump’s hands by seldom mentioning the religious affiliation of the San Bernardino and Orlando killers. But President George W. Bush had a similar reluctance because he didn’t want the “war on terrorism,” as he called it, to be confused in the Muslim world with a “war on Islam,” which is how radical groups seek to portray Western counterterrorism efforts. Abroad, just as at home, the U.S. needs to win the cooperation of the vast, moderate Muslim majority if we are to identify the handful of terrorists in their midst. Alienating ordinary Muslims with rhetorical assaults on Islam, as Mr. Trump does, is as foolish as it is counterproductive.

That said, Mr. Obama’s reluctance to discuss more openly the problem of jihadist attacks is indicative of a major shortcoming of his presidency—the lack of urgency he feels in waging wars, even when core U.S. interests are at stake. Determined not to be a wartime president, he has never put enough resources, willpower or momentum behind efforts to defeat groups such as the Taliban or Islamic State. Even when he ordered a surge of forces into Afghanistan in his first term, he put an 18-month deadline on their deployment, encouraging the Taliban to wait them out.

Islamic State, to which Omar Mateen pledged allegiance just before the Orlando massacre, might never have been formed if Mr. Obama had not pulled U.S. troops out of Iraq in 2011 and stood by as Syria devolved into civil war. The resulting power vacuum on both sides of the Iraq-Syria border allowed Islamic State to capture the key Iraqi cities of Mosul and Ramadi and to proclaim a caliphate in the summer of 2014. The president appeared oblivious to the danger, deriding Islamic State as a “JV team” compared with the varsity squad, al Qaeda.

That August, when Mr. Obama finally agreed to bomb the group’s positions, he did so with such tight restrictions on “collateral damage” that two-thirds of the aircraft, according to Central Command, returned to base without having dropped any bombs. He also prevented the military from putting “boots on the ground,” even though embedding U.S. troops with local forces is the surest way to increase their fighting effectiveness.

Gradually, those restrictions have been relaxed, allowing U.S. Special Operations Forces to go into the field and increasing the pace of American bombing. As a result, the U.S.-backed coalition has had growing success, most recently wresting Ramadi from Islamic State’s control. Iraqi forces are now retaking control of Fallujah, but Mosul remains in the hands of Islamic State, as does the group’s Syrian stronghold of Raqqa. And even as the territory under the group’s control shrinks, its propagandists continue to beseech Muslims abroad to carry out attacks in their homelands. The longer Islamic State manages to hold on, the more of an attraction it exerts for potential jihadists such as Mateen.

Online counter-radicalization efforts are another important priority, given how much Islamic State relies on internet propaganda. But the internet is too vast and varied to be policed effectively. The only way to curb the appeal of Islamic State is to capture its safe havens in Iraq and Syria and destroy it. Even suicidal terrorists don’t want to die in a losing cause, and Islamic State’s recruiting has declined along with its military fortunes.

We will defeat Islamic State not simply by dropping more bombs or sending more troops, although we must do both. The other imperative is to woo anxious Sunnis in Syria and Iraq away from Islamic State by offering them a political end-state they can support—one that doesn’t involve domination by Shiite Iran or its proxies. This has been the most blatant missing element of Mr. Obama’s strategy against Islamic State. Only by reaching out to Sunnis, as U.S. commanders did during the “surge” in Iraq in 2007-08, can they be convinced to abandon their support for Sunni terrorist groups like Islamic State.

Even if Islamic State is destroyed, however, no one should imagine that attacks such as the one in Orlando will simply come to an end. Islamic State could disappear tomorrow and there would still be plenty of Islamist firebrands eager to recruit followers for terrorist attacks in the West.

The ultimate solution to the rise of Islamist terrorism must involve a revolution of thinking in the Islamic world similar to the Reformation in Europe. The U.S. has a limited capacity to bring that about but must do what it can by backing Muslim moderates—and, yes, they do exist. Tunisia has become a democracy, and its Ennahda party has eschewed Islamism—that is, religious rule—to become a “Muslim Democratic” party, echoing Europe’s Christian Democratic parties. That is a small but hopeful development.

While we wait for the gradual transformation of the Muslim world, we must combine enhanced efforts at domestic security with enhanced efforts to deny terrorists safe havens abroad. Unfortunately, a great many places—Pakistan, Afghanistan, Iran, Iraq, Syria, Libya, Yemen, Somalia—now fit this description.

It is a big task to clean up such deeply troubled places, and it won’t be done by invading country after country. The long war ahead will be fought by a variety of means, some of them military, many not. Our challenge resembles the Cold War, another multigenerational struggle waged with many different allies, not only on battlefields but also in the battle of ideas. We can only hope that someday the war on terror will end just as peacefully.