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:
+---------------+------------------+-----------------+
| Star Coin Req | Max w/o Op. Lvls | Max w/ Op. Lvls |
+---------------+------------------+-----------------+
| 50 | 66 | 81 |
| 90 | 105 | 135 |
| 100 | 108 | 141 |
+---------------+------------------+-----------------+
(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.