Reputation: 1150
I'm trying to implement pagination for my posts. Though I'm a bit stuck on the php function and also how to call it.
The simple method is this I guess:
<?php posts_nav_link(); ?>
But what if I want custom pagination?
Here is my current code:
<?php
global $wp_query;
$total = $wp_query->max_num_pages;
if ( $total > 1 ) {
if ( !$current_page = get_query_var('paged') )
$current_page = 1;
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'list'
));
}
?>
Is this correct and how do I call it? In index.php? Where in the loop? Thanks.
Edit for clarification: How do I implement this code? At the moment I have put it in my functions.php. So how (and where in the loop) do I 'reference' this function so the pagination is displayed.
Upvotes: 0
Views: 4261
Reputation: 1846
There are two ways you can implement this code. It looks like right now you are sort of in between the two.
The first way would be to add your pagination code directly into the template that it will be used in somewhere inside the loop (most likely somewhere right before the closing <?php endwhile; ?>
tag). If you are using a single.php template, you would put it in there, if not, put it in index.php. The placing of it inside of the loop depends on where you want the pagination to appear on your page.
The second way is to add the pagination code to the functions.php file (which you have done). However, you will need to revise your code a bit for this. You need to wrap the code within a function, and name that function something. I've used your_custom_pagination
for an example. Your functions.php file is most likely already wrapped in php tags, so I have removed those.
function your_custom_pagination() {
global $wp_query;
$total = $wp_query->max_num_pages;
if ( $total > 1 ) {
if ( !$current_page = get_query_var('paged') ) {
$current_page = 1;
}
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'list'
));
}
}
Then you'll need to go into the template that you are using and place this code <?php your_custom_pagination(); ?>
into the same spot I illustrated above to call the pagination function.
I haven't actually tested your code, so assuming it's valid everything should work.
Upvotes: 3