Why didn’t Lord Shiva realize that he was beheading his own son?
This whole event is a series of interconnected Chain events. I'm here summarizing the chain events:
1) Boon to Gajasura:
Gajasura was a devotee of Lord Shiva and he got a boon that his head would be revered in future as described in the answer here.
2) Curse to Lord Shiva:
Lord Shiva once killed Surya and Kasyapa (father of Surya) cursed him as described in answer here.
He struck Surya with a trident and this made the entire world plunge into darkness. Surya was the sage Kashyapa's son and so, for this act, Kashyapa cursed Shiva. "Just as you pierced my son's chest with a trident, your son's head will be chopped off one day," said Kashyapa.
3) Son of Shiva-Shakti:
Ganesha (Vinayaka) was only son of Prakriti tatwa as made only by Parvati. Lord Shiva transformed Purush tatwa to Vinayaka from his Trishula while beheading him. And thus he philosophically became son of both Shiva and Shakti.
4) Removing Maila Buddhi:
Ganesha was formed from dirt/mud by Parvati. So his intellect had also became dirt formed intellect. As a result he couldn't recognise the Supreme Shiva and other Gods, Sages also. So, Beheading the head removed the dirt formed intellect and it also removed only Maya/Prakirti/Parvati formed intellect.
These all events described above are interconnected as Chain events. So, Beheading Vinayaka (Ganesha) by Lord Shiva was necessary.
Note: “The question: Why didn’t Lord Shiva realize that he was beheading his own son?” is licensed by Stack Exchange Inc (https://hinduism.stackexchange.com/); user contributions licensed under CC BY-SA.