Instead of the loop at the bottom, use WordPress’s paginate_links()
:
$pagination = paginate_links(array(
'total' => $pages,
'current' => $page
));
echo $pagination;
You can play around with some of https://codex.wordpress.org/Function_Reference/paginate_links to get the appearance the way you want. Specifically, the end_size
and mid_size
will help you to determine the number of page numbers that show, as in your example (1 2 3 … 11).
If you want something really powerful, you can check out my Boone’s Pagination plugin: http://teleogistic.net/2011/05/new-wordpress-plugin-boones-pagination/ (shameless plug!), though it may be too much for your use case 🙂