Chocolate bars are displayed for sale at the Hershey Co. Chocolate World store in Hershey, Pennsylvania, U.S., on Friday, July 13, 2018.

Hershey agreed on Wednesday to buy Pirate Brands from B&G Foods for $420 million in an all-cash deal, giving the chocolate maker rights over snack brands such as Pirate's Booty, Smart Puffs and Original Tings.

The deal is expected to add to Hershey's financial targets as it delves into the more than $2.5 billion cheese puffs market, the company said in a statement.

Hershey intends to finance the transaction with cash reserves as well as short-term borrowings and expects the deal to close in the fourth quarter of 2018.

B&G Foods, which bought Pirate Brands in 2013 for about $195 million, said it would use the net proceeds from the sale for repaying its long-term debt and for funding possible acquisitions.

B&G Foods rose nearly 1 percent to $32.15 and Hershey shares were inactive in after-hours trading.