If we're talking about retroviruses, there's a long and complicated answer i.e. for HIV (see https://en.wikipedia.org/wiki/HIV_integration) and a short one: after reverse transcription DNA in the context of viral enzymes enters the nucleus. The viral enzyme integrase then mediates the insertion, which essentially is a non-random process. If you genetically engineer a gene of interest in your viral genome, it will be integrated with the genome and provide efficient stable integration (and hopefully expression) of your gene of interest.