With Spock mostly back in one piece following some months of rehabilitation on Vulcan, the Enterprise crew decide to take their captured Klingon vessel back to Earth and face the music for their mutinous behavior in Star Trek III.
As they approach Earth, though, things are a little messy in San Fransisco. A huge, unidentified alien probe is parked in orbit. It's affecting everything, planetwide, from the weather to power systems. The Earth will die, Kirk surmises, unless they can do something about it. Uhura intercepts the message the device is sending out, and Spock matches it against computer records of various other Earth species' vocalizations. He determines that the message was meant for humpback whales, long extinct from the planet's oceans.
Kirk thus decides to take the ship back in time to 20th century Earth, with the hopes of bringing a couple of whales back with them so they can communicate with the alien device.
In 20th century Earth, they gather the materiel necessary to make the transport, and are greatly assisted by a local whale expert, desperate to save the lives of a male and female couple that have recently left her care for the wild.
After a series of generally humorous adventures by the scavenging Enterprise crew, they successfully bring two 20th century whales (and their caretaker) to the 23d century. This ends the probe's disturbance of Earth's weather and power grids, effectively saving the planet from destruction.
In appreciation for saving the planet yet again, Kirk's trial for mutiny goes largely in his favor. Over the protests of the Klingon Ambassador, Kirk is reduced in rank from Admiral to Captain, and restored to his status as Captain of a newly-built Enterprise, NCC-1701-A.