4

I'm creating pagination for my site. Hope everyone can explain to me what below code used for? Thanks in advance.

<?php
if ( get_query_var('paged') ) {
    $paged = get_query_var('paged');
} elseif ( get_query_var('page') ) {
    $paged = get_query_var('page');
} else {
    $paged = 1;
}
query_posts('paged='.$paged.'&posts_per_page=');
?>
10

I hope you understand what query variables is. If not, here is it in short. The main query uses WP_Query to set itself up. In the main query, WP_Query uses public query variables to construct the main query according to the page being requested, and paged and page are two of them. To see all the public query variables, paste this in your header and check on all templates how this are set according to the queried page

var_dump($wp_query->query_vars);

The function get_query_var() is used to get the values from those public query variables, and in this case that is page and paged.

To answer your question, these two parameters and its values are used by WP_Query to calculate pagination and more importantly the offset of posts according to page numbers. It is this parameter that ensures that your posts page correctly when paging through pages

  • paged -> Used on the homepage, blogpage, archive pages and pages to calculate pagination. 1st page is 0 and from there the number correspond to the page number

  • page -> Use on a static front page and single pages for pagination. Pagination on these pages works the same, a static front page is treated as single page on pagination. By pagination on single pages, I mean that single posts can be broken down into multiple pages

What your code basically does is, it checks if the paged parameter is set, if that fails, it checks whether the page parameter is set, and if that is not set, set the page to 1. This check will always fail on page 1, so $paged will always fall back to 1. On any other page than page one, either paged or page will return true and sets $paged to the correct page number

Final note: Never ever use query_posts unless you need to break something on your page, and believe you me, you don't want that. Always use WP_Query for paginated custom queries. For a full explanation on this, please see this post I have done a while ago

  • Thank @pieter-goosen It's really nice explanation. Is paged used to get current page which viewing? – Hung PD Mar 12 '15 at 2:04
  • 1
    Yes, you can use echo get_query_var( 'paged' ); to get the current pagenumber you are viewing – Pieter Goosen Mar 12 '15 at 3:27
  • Great explanation! The page param takes the <!--nextpage--> keyword into account, which breaks up a single post into multiple pages: en.support.wordpress.com/nextpage/view-all – Philipp Aug 13 '19 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.