Why is the play made by Hamlet in the story of "Hamlet"?
Hamlet inserts his rewritten lines into the play the players will perform. He does this because he wants to be sure that the ghost was indeed the spirit of his father, and not a devil trying to lure him into hell (Act 2, sc. 2 soliloquy). He says he's heard that guilty people will be startled by seeing their actions performed in a play, so he figures that if Claudius reacts to Hamlet's rewritten scene that will depict his father's murder, then Claudius did, as the ghost said, kill King Hamlet. Hamlet has asked the lead player if they could insert lines he, Hamlet, has written into the play and the player agrees to do it. When the play is performed in Act 3, sc. 2, and Claudius does react in a startled manner, Hamlet is convinced the ghost was the spirit of his dead father and it was telling him the truth.
I agree with the previous answer but with Hamlet you always have to bear in mind that procrastination is a possibility too. He seems to love playacting and striking poses, and welcomes the players very warmly, so it is natural that he would take to a scheme like this but it also postpones for another while any action that he is going to take against Claudius.