Is it true that the heavens and the earth were created only for the sake of Muhammad (peace be upon him)?
This is not true because Allah (Exalted be He) created the jinn (creatures created from fire) and mankind for the sole purpose of worshipping Him alone, without associating any partners with Him. Allah (Exalted be He) says (what means):
And I (Allâh) created not the jinn and mankind except that they should worship Me (Alone).
He made all that is in the heavens and on the earth in the service of His slaves. Allah (Exalted be He) says:
And has subjected to you all that is in the heavens and all that is in the earth
Allah created the heavens and the earth so that His slaves may know the Perfection of His knowledge and Power, as He (Exalted be He) says:
It is Allâh Who has created seven heavens and of the earth the like thereof (i.e. seven). His Command descends between them (heavens and earth), that you may know that Allâh has power over all things, and that Allâh surrounds all things in (His) Knowledge.
As for the Hadith you referred to, it is Mawdu‘ (fabricated) and its authenticity is denied, as appraised by the scholars, among them
Al-Dhahaby. May Allah grant us success. May peace and blessings be upon our Prophet Muhammad, his family, and Companions.