Tuesday, January 11, 2011

Pagination in wordpress

If we have a large number of posts in wordpress , its not good to list all posts in a single page. So we need to restrict the listing of the posts. The query_posts() returns posts from the database . The main disadvantages of query_posts() is the lack of pagination .We can use parameters to change the listing of posts. Suppose we have a number of 50 posts in our site, it’s better to use pagination in the site. Here am trying to explain about how to use pagination in wordpress with query_posts().

First we need to install a plugin for pagination. We can use WP-Paginate plugin for pagination. We can download the plugin from the following link http://wordpress.org/extend/plugins/wp-paginate/ and install the plugin.

Add the following code in the page where you want to set pagination links.

<div class="navigation_nav">
<?php if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

The above code will generate pagination navigation in the post page.

Next is to set the parameters for the query_posts(). We need to get the current page number and the pagination page number.

Add the following code before query_posts() to get the page number.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
The above code get the page number from the GET variables. If the variable is not set , the page number is set to 1;

Next we need to pass the parameters to query_posts(). Use the following code to pass the parameters to query_posts().
query_posts("&paged=".$paged)
This will display a pagination link in the post page. We can set the number of posts to display by setting the 'posts_per_page' variable.
Similar as follows
query_posts("&paged=".$paged."&posts_per_page=10")
Also we can set the property in the admin side.

To set the post per page using admin panel
Go to Settings -> Select Reading -> edit 'Blog pages show at most' to your number.
But priority for post per page will be with the code that we added in the page.

Full source code:

After applying the codes the page will be similar as follows.


<?php
// get the page number and get the posts
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$q = "paged=".$paged.'&posts_per_page=2';
query_posts($q);
?>

<div class="navigation_nav">
<?php
// pagination links
if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

<?php
// listing of posts
if (have_posts()) :
while (have_posts()) : the_post();
$custom_fields = get_post_custom(get_the_ID());
?>

No comments:

Post a Comment