Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) says that the Messenger of Allah (peace and blessings be upon him) entered a grave at night, and a lamp was lit for him (peace and blessings be upon him). He took him (the deceased) from the direction of the qiblah and said four takbirs, then said: "May Allah have mercy on you! You were indeed forbearing and a reciter of the Qur'an."
This chain is weak, and it has also been narrated through another weak route from Ibn Mas'ud. But what Imam al-Shafi'i (may Allah have mercy on him) mentioned is widespread in the land of the Hijaz; the later generations took this practice from the earlier ones, and it is more worthy of being followed.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الجنائز / 7057