The Israelites have started having sex with the women of Moab, and worshipping their gods. Jerry Falwell tells us that the Canaanites practiced prostitution in their religion, conveniently forgetting Judah's little dalliance with his daughter-in-law Tamar.
God gets pissy and tells Moses to hang the men who started worshipping the other gods in the sun. That must have been a lovely, and pungent reminder of god's mercy.
Next, an Israelite man marries a Midianite woman. Now, you may remember from Exodus chapters 2-4 that Moses' wife Zipporah is a Midianite. So no problem, right? No, god now unleashes a plague upon the people. Fortunately, Phineas the zealot takes a javelin and stabs the couple to death. 24 000 people still die. This settles god down, and he makes Phineas the new priestly line. He then instructs Moses to beat the Midianites.