Are songs written for anime openings or endings? I know that some songs in anime openings or endings come from popular J-Pop singers/albums (such as the Bleach opening Rolling Star by Yui). However, some opening songs seem to show up during the show, such as themes appearing during final battles. Are opening or ending themes generally written specifically for the show or are they taken from popular Japanese songs.
In most cases, yes.

A popular example of this is the anime K-On!. All the openings, endings and insert songs are written for the anime itself. They use the anime to advertise it and to sell more. Here is the list of the anime's albums which if you observe, are really dedicated for the anime itself. It even had two live concerts, Let's Go! and Come With Me where the seiyuu of each character actually played their character's instrument. Well K-On! has a plot that revolves around band members so it would be just appropriate to focus more on creating songs specifically for the anime's plot.

To prove that most anime theme songs (opening, ending, insert songs) are written for the anime itself is the existence of Image Song orCharacter Song. 


  An image song or character song is a song on a tie-in single or album (often called an image album or character album) for an anime, game, dorama, manga, or commercial product that is usually sung by the voice actor or actor of a character, in character. It is meant to give a sense of the personality of the character.


So it would be more appropriate to write character song depending on the anime character's personalities and his/her situation on the anime he/she belongs to. 

This article explains further about it and it also sites more detailed examples.