The chords are usually written to the melody of a composition. Any given chord of a composition will usually contain one or more of the notes from the melody within its triad. The subsequent chord progression of the composition is the ultimate outcome of the pairing of the chords to the melody. This combination of melody and harmony is where some real magic happens...
One can play the melody's underlying chords in various ways to achieve different effects:
Or, substitute the underlying chords entirely to create an almost original-sounding tune:
I'd suggest getting all of the academic parts of chord theory under your belt (LOTS of good posts here and other info on the Interwebz.) Then, pick a favorite melody, learn the chords, and go about practicing the variations. Then try to begin writing new chords under your chosen melody.