The nation of Moav heard about Bnei Yisroel coming, and they were seized with fear. For many years, they had known “all that HASHEM had done for the Jewish people while taking them out of Mitzrayim,” and they were well aware that the land of Israel was consecrated for the Jews. Now the inevitable was coming to fruition.
Recognizing that there was little hope in waging war against the Jews, Balak, the king of Moav, hired Bilaam to curse the Jews. However, not only didn’t Bilaam curse the Jews, he gave them a bracha, saying the prophetic words: “Ma tovu ohalecha Yaakov.” When Balak confronted Bilaam about this, Bilaam’s truthful response was, “It is not in my power to curse them. But if you want advice in fighting this nation, you must get HASHEM to be angry with them. Their G-d hates promiscuity. If you can get them to sin, you can conquer them.”
With that was launched a fatal attack against the Jews. Balak sent out the Bnos Moav to entice the Jewish men. The plot was successful and thousands of Jewish men succumbed. At the height of the debacle, Zimri, the head of Shevet Shimon, took a Moabite woman into the very camp of Israel and publicly committed a sin with her. When Pinchas saw this, he stood up, and at the risk of his life, miraculously killed them both.
After the events, the posuk describes HASHEM saying, “Pinchas took my revenge amongst the people, and now I do not have to destroy the Jewish nation.” The Siforno explains that because the entire nation saw what had transpired and didn’t act, they all deserved to die. By acting in public for all to see, Pinchas atoned for their sin, and now HASHEM didn’t have to kill out the nation.