During the Mexican–American War, Baker briefly dropped out of politics and was commissioned as a colonel of the Fourth Regiment of the Illinois Volunteer Infantry, on July 4, 1846. In the Battle of Cerro Gordo, the regiment was assigned to General James Shields's Illinois brigade in General David E. Twiggs's division. When Shields was badly wounded in an artillery barrage, Baker boldly led the brigade against the entrenched artillery battery, resulting in the capture of the guns. General Winfield Scott later said, "The brigade so gallantly led by General Shields, and, after his fall, by Colonel Baker, deserves high commendation for its fine behavior and success." Soon after Cerro Gordo, the enlistment period ended for men of the 4th Illinois and they returned to New Orleans and were discharged on May 25. Baker returned to Springfield in 1848, but, rather than run against Lincoln again for nomination to Congress, Baker moved to Galena, where he was nominated and elected as a Whig to the 31st Congress (March 4, 1849 – March 4, 1851). He was not a candidate for renomination in 1850.