In a situation where one has 20 posts per page. I would like to get the current page number in order to make some nice page links at the bottom. How do you get the current page. I tried this
<?php echo '(Page '.$page.' of '.$numpages.')'; ?>
and it just says page 1 of 1 on every page.
Any ideas,
Marvellous
When WordPress is using pagination like this, there’s a query variable
$paged
that it keys on. So page 1 is$paged=1
and page 15 is$paged=15
.You can get the value of this variable with the following code:
Getting the total number of pages is a bit trickier. First you have to count all the posts in the database. Then filter by which posts are published (versus which are drafts, scheduled, trash, etc.). Then you have to divide this count by the number of posts you expect to appear on each page:
I haven’t tested this yet, but you might need to fetch
$posts_per_page
the same way you fetched$paged
(usingget_query_var()
).You could do it with a single line of code, but then again, you might want to add the code in other places, so a function is usually more useful.
NOTE: Code can go into your functions file.
Simply call the function where you want to show the “Page x of y” message, eg.
If you need the code to work with a custom query, ie. one you’ve created using
WP_Query
, then simply pass along the name of the variable that holds the query to the function.Example non-existant query:
Getting the current page for the custom query using the function posted earlier..
If you want to just totally forget the custom query support and you’re looking for a one-liner, then this should do it..
Hope that helps.. 🙂
From wordpress documentation
paginate_links( string|array $args = '' )
:This will list the page numbers and Next post, and Previous post. You need to post this link on the pages where you want the page numbers to be displayed.
As mentioned above – a simpler way to get the max number of pages is with:
One option that works on all my archive pages is this:
First query if there is more than one page in this
wp_query
, then concatenate title with current page via$paged_current_page
and total pages with$title_page_nrs
. Lastlyecho
it. If above 1 page first, thenelse
if is not paged. This goes into my archive.php or templates for this type. It produces:<title>Taxonomy title - page nr 1 of 4 | Your Website Name</title>
or
<title>Taxonomy title | Your Website Name</title>