Pagination for custom query in WordPress

WordPress is good at taking care of pagination automatically if you are displaying all the posts. But incase if you have a custom query to retrieve results for example: all posts from a certain category then the default pagination does not display the next page of posts. Instead, it displays the same posts again. However, there is a way to get pagination (paging as some call it) with a custom query.

Following code will take care of the pagination:

$page = (get_query_var("paged")) ? get_query_var("paged") : 1;
$wp = new WP_Query();
$wp->query("category_name=CATEGORY_NAME&paged=$page");
while ($wp->have_posts()) : $wp->the_post();

<!-- Display your posts here -->

<?php endwhile;?>