Pagination breaks if inside an if