And he (peace and blessings be upon him) also said, “Do not pray facing graves, and do not sit on them.” This ḥadīth was recorded by all six major compilers except al-Bukhārī. He (peace and blessings be upon him) further said, “So do not turn graves into places of worship.”
The reason for forbidding prayer in graveyards or beside them is not a fear of ritual impurity; it is the fear that the graves might be venerated and taken as idols. In other words, the prohibition is meant to block the means that could lead to worshipping those who are buried.
An exception is made for the funeral prayer: it is permissible to offer it in the cemetery because the Prophet himself did so, and his practice restricts the general ban. Everything that falls under the designation “graveyard,” including the surrounding area adjacent to the graves, is likewise a place where prayer is not to be performed, for the prohibition applies to both the cemetery proper and the space around it.