Temporary marriage, (mut`ah) is unlawful by consensus as stated by Ibn `Abd al-Barr in al-Istidhkâr (5/508). He writes: “All scholars of reason and revelation agree on the unlawfulness of temporary marriage, because the prohibition of the Prophet (peace be upon him) regarding it is authentic.”
One of the hadîth that prohibit such marriage is through Sabrah al-Juhanî. He said: I was with the Prophet (peace be upon him) when he said: “O people I have allowed you earlier to marry women on a temporary basis, but Allah has now forbidden it until the Day of Judgment. So if any of you have a woman from that kind of marriage, let him release her and do not request any refund of what you have given them.” [Sahîh Muslim]
In his commentary of Sahîh Muslim, Imam al-Nawawî comments (9/179): “Al-Mâzirî said : 'It was authentic that temporary marriage was permissible in the early days of Islam. Then it was abrogated by authentic hadîth. It is the consensus now that it is unlawful. All Muslims abided by this except one group of innovators.' He was referring to the Shî`ah.”
Al-Nawawî also says: “The truth is that this prohibition and permission took place twice. It was lawful before Khaybar, then prohibited on the day of Khaybar. Then it was permitted again on the day of Makkah - the day of Awbâs - which was close. Then, again, it was forbidden after three days until the Day of Judgment.”
This kind of marriage was lawful for a certain reason. The Companions were new in Islam and were suffering from physical needs. There were not many women at certain times and this kind of marriage was needed.
`Abd Allah b. Mas`ûd said: “We were fighting along with the Prophet (peace be upon him) and did not have women. We asked: Shall we castrate ourselves? The Prophet (peace be upon him) prevented us from that but he allowed us to contract marriages with women for a certain period of time by giving them something, clothing or the like.” [Sahîh al-Bukhârî and Sahîh Muslim]
Many scholars referred to this reason. Ibn Hajr writes: “It is as mention by al-Ismâ’îlî that there was fighting and a lack of women.” [Fath al-Bârî (9/170-171)]
It was related that one time Ibn `Abbâs declared that temporary marriage was lawful. Then one man told him: “Temporary marriage was permitted in the early days of Islam to whom it was needed, the same as carrion, blood and the flesh of swine. It was permitted out of need.” (Ibn `Abbâs did not object). This is the answer to your question.
And Allah knows best.