How to ignore WordPress pagination and display all posts on a page →

Posted on January 19, 2012 in Development with 2 comments.

There are times when you want to display a list of WordPress posts (or even custom post types) on a page and not have them paginated into multiple different WordPress pages. For example, you may be creating an archive page and instead of showing just the latest 10 posts in your category, you want to show the whole list of posts in that category.

I recently come across this challenge when building the theme for this site and it is actually very easily overcome. You just need to add a little bit of PHP code to your theme file.

Let’s assume we are working on an archive page (archive.php in WordPress). In that file you have your standard WordPress loop which will display the latest 10 posts (or however many you have set to display per page in your WordPress settings). So we have something like this…


<php
if ( have_posts() ) : while ( have_posts() ) : the_post();
	// Your code here
endwhile; endif;
php>

Now, to avoid showing just the latest 10 posts, we need to do this


<php
global $query_string;
query_posts( $query_string . '&posts_per_page=-1' );
if ( have_posts() ) : while ( have_posts() ) : the_post();
	// Your code here
endwhile; endif;
wp_reset_query();
php>

Simple enough. All we added was 3 extra lines of code.

Firstly, we reference the $query_string global so that we can use it in the code. Then we use the existing query string that was set to fetch the posts and add an extra parameter to the end of the query string called “posts_per_page” to display a custom number of posts, in this case we use -1 to display all posts. And lastly, we reset the query after we are done.

Tagged with

2 Comments

  1. Why not use the recommended way to pull posts?

    $args = array(
    ‘nopaging’ => ‘true’,
    [...]
    $query = new WP_Query( $args );

  2. Matt says:

    Hi Zeno,

    You would generally use WP_Query if you are wanting to create a new query from scratch, not modify an existing WP Query. The example above assumes that you want to modify an existing archive/post_type page.

    From the WP docs:

    “query_posts() is the easiest way to alter the default query that WordPress uses to display posts.”

    http://codex.wordpress.org/Function_Reference/query_posts

    Matt

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>