Is it possible to buy an entrance pass to Yosemite Park in advance or will I need to purchase it when I arrive?
You just pay the fee directly to the ranger when you drive in. The price increases on June 1st to $35 for a 7-day pass.
IF (big if) you are going to several National Parks or federal lands over the next 12 months, then it might make sense to buy an $80 America the Beautiful federal lands pass. Again, just pay at the entrance gate.
Even if you pre-buy the America the Beautiful pass, everyone drives through the same entrances, so there's no 'skip the line' benefit. Having the pass in hand makes your processing slightly faster, buying it on the spot makes the processing slightly slower. Not enough to make a difference.
And, if you happen to arrive in Yosemite for the first time either early enough in the day before the rangers are staffing the entrances or later enough that they've gone home, you can just come in and then pay your fee when you leave.