There are an interesting number of levels that are locked without a certain number of Star Coins. For the most part, you seem to be able to pass these levels by and just play the next level (with the exception of one of the Bowser's Castle levels, I think).
Do I need to unlock all of these levels to finish the main story part of the game? (Or do they just count towards one of the 5 shiny stars you need to get the Final Level?)
Best Answer
The main story part of the game concludes when you clear the final castle in world 8. It doesn't matter how many levels you go through to get there.
That said however, you might want to go through the optional levels just for the Star Coins they have. There are three castles that require certain amounts of Star Coins: one needs 50 while the last two need 90 and 100. I did the math, and while there is a buffer, you have to be pretty thorough at getting Star Coins if you intend to avoid optional levels altogether:
(The numbers are how many Star Coins you can have before entering the level, counting only the 3 Star Coins per preceding mandatory level.)
So while the optional levels are technically optional, to finish the main story you'll probably want to go through them.