How did WASP-18b exoplanet form?
@LocalFluff's comment is more-or-less complete. The process of "swapping" planets between stars could happen during the early lives of stars when most of them are born in relatively dense clusters. You can find some more details and references in my answer to this question, but the outcome is that a captured planet would usually be in a very wide orbit.

Approximately 1% of stars have a "hot Jupiter", but even in dense cluster environments it is thought that only a few percent of stars can capture a planet, and because almost all of these end up in wide orbits there are just too many hot Jupiters to be explained in this way.

There are two classes of theory to explain hot Jupiters. One is the dyanmical explanation offered by LocalFluff. This is itself divided into several different mechanisms: "Secular chaos", (e.g. Wu &amp; Lithwick 2011 - this paper also briefly reviews some of the other mechanisms) which is a gradual change in the planetary system that then suddenly drives a transition to a new configuration. Planet-planet scattering where interaction between planets causes one orbit to become highly eccentric and then tidal circularisation results in a hot Jupiter in a close orbit (e.g.Ford &amp; Rasio 2008). The Kozai mechanism is the interaction beteen two planets that results in an interchange between the inclination and eccentricity of the inner planet. This excites an increase in eccentricity that, when combined with tidal circularisation, can  also result in a close-in planet.

The other class of mechanism involve migration through interaction with a disk. This must necessarily happen early in the star's life whilst surrounded by a disk of circumstellar material. Basically viscous drag in the disk itself causes the planet to move inwards (or sometimes outwards). There are three possible subtypes of disk migration and they are briefly defined here.

It is probable that all of these mechanisms play some role in forming hot Jupiters and one of the goals of exoplanetary study is to figure out which may be more important. Typical parameters of interest are the distribution of planetary orbits and eccentricities and whether there is evidence of previous interactions in the form of misalignments between the rotation axis of the star and the orbital axis of the planet.