A woman said, "Messenger of Allah, this son of mine, my womb was a vessel for him, my breast a drink for him, and my lap a shelter for him. His father has divorced me and now wants to take him away from me."The Messenger of Allah ﷺ said to her, "You have the greater right to him as long as you do not remarry."
أن امرأة قالت: يا رسول الله! إن ابني هذا كان بطني له وعاء، وثديي له سقاء، وحجري له حواء. وإن أباه طلقني، وأراد أن ينتزعه مني! فقال لها رسول الله ﷺ: أنت أحق به ما لم تنكحي.
It was narrated by Abu Dawud (2276), Ahmad (6707), Daraqutni (3/305), Hakim (2/20), and from him Bayhaqi (4/8-5), all of them through routes going back to Amr bin Shuayb, from his father, from his grandfather, who related it. Hakim said, "Sahih Isnad." Its isnad is hasan because of Amr bin Shuayb, for he is hasan al-hadith.There is no disagreement among the scholars that the mother has custody of the child as long as she does not remarry. If she remarries, she has no right to custody of him. If she has a mother, then her mother takes her place. Then the grandmothers on the mother's side have the greater right to him for as long as any one of them remains.