Fearing Taliban threats, President Ashraf Ghani of Afghanistan has mostly campaigned for re-election via Skype, reaching voters outside Kabul through “virtual rallies.”

But on Tuesday, the president risked a 35-mile trip from the capital to neighboring Parwan Province for a rally inside a police training compound. And there, just as the rally started, the Taliban made good on repeated vows to attack anything connected with the election, scheduled in less than two weeks.

A suicide bomber on a motorcycle blew up as people waited to be ushered into the heavily guarded compound. At least 26 people were killed and 42 were wounded in the late-morning attack, the Ministry of Interior said. Mr. Ghani, who was inside the compound, at least a half-mile from the blast, was unhurt.