Wordpress services, tutorials and news

Custom pagination for WordPress

When you have a list of posts, by default WordPress shows 10 posts. What if you want to have more or less posts shown on a page, or a custom number of posts for each post category?

First thing to know is  that if you want to change the number of posts shown in a list in the entire WordPress site you can do this from the dashboard. head over Settings/Reading and you can change the number of posts at “Blog pages show at most”.

How to set a custom number of posts on a WordPress page

If you want to show a custom number of posts on a particular page, first thing to do is to locate where the post list is built. It can be in more places: index.php, archive.php or custom templates. To find out where the list is built you can simply echo “text”; in the php files until you find out the php page that is used. Then we need to change the custom loop in a way that takes into consideration the number of posts. This is the custom loop:

<?php if ( have_posts() ) : ?>
	<?php while ( have_posts() ) : the_post(); ?>    
	<!-- do stuff ... -->
	<?php endwhile; ?>
<?php endif; ?>


We need to add arguments to the loop to change the default number of iterations in the loop. To do this, first we define an array that holds the arguments, for example see in bold:

<?php $args = array(
‘paged’ => get_query_var(‘paged’)
); ?>

The next step is to change the standard loop to apply the new arguments:

<?php $wp_query = new WP_Query( $args );

if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();

<!– do stuff … –>

<?php endwhile; ?>

<?php endif; ?>

This is great, but at this step you can’t navigate to the next/previous posts. We need to add the paginate links using previous_posts_link and next_posts_link. Here is how it should look:




Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress templates