This work presents the extension of a compact finite difference immersed boundary method for the detailed calculation of fluid flow and heat transfer in porous media. The unsteady incompressible Navier-Stokes and energy conservation equations are solved with fourth-order Runge-Kutta temporal discretization and fourth-order compact schemes for spatial discretization, which allows achieving highly accurate calculations. Verification proves that the method is higher than third-order accurate. Three test cases were used for the validation of the method: (i) isothermal flow around a square cylinder in a plane parallel channel, (ii) isothermal flow through an infinite row of square cylinders and iii) flow and heat transfer around a square cylinder in a plane parallel channel. The validation tests establish confidence in the application of the method to porous media. As an example of such an application, direct numerical simulations are conducted for a staggered array of equal size square cylinders. Although the problem is rather complex from the geometrical point of view, a Cartesian grid is employed, with all its advantages. The potential of applying an immersed boundary method to the solution of a multiphase problem with complex internal boundaries is demonstrated.