Add pagination to posts and refactor code