Ok, I’ve a custom post type page to which I have attached the paginate_links
function to navigate through the elements.
If I don’t do anything and let WP using whatever mechanism is attached to the archive page, then the paginate_links
work fine but the previous link never goes back to the page one.
Changing manually the links works fine.
On the contrary, if I do something like the answer suggested here, overriding the wp_query
object, the paginate_links
move to the second page but the “current” remains set always on page 1.
CODE
$current = get_query_var('page') ? get_query_var('page') : 1; // Get query var
$record_per_page = 2; // How many faqs to display on each page
$offset = ( $current - 1 ) * $record_per_page;
$args = array(
'post_type' => 'faqs',
'orderby' => 'date',
'order' => 'desc',
'page' => $current,
'offset' => $offset,
'posts_per_page' => $record_per_page,
);
$the_query = new WP_Query( $args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $the_query;
$row = 1;
$total = ceil(wp_count_posts('faqs')->publish / $record_per_page);
while ( have_posts() ) : the_post();
echo get_the_ID();
endwhile;
// Reset postdata
wp_reset_postdata();
if ( $total > 1) {
$paginate_links = paginate_links( array(
//'base' => @add_query_arg( 'page', '%#%' ),
'base' => '%_%',
'prev_text' => __('« Indietro'),
'next_text' => __('Avanti »'),
'mid_size' => 5,
'format' => '?page=%#%',
'current' => $current,
'total' => $total
)); echo $paginate_links;
}
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
Any idea of what’s happening?
2 Answers
Ok, the issue seems to be connected with the base and format parameters. I may not able to explain properly technically what has happened.
However, from what I see in my archive page, my page parameter is by default “page” and not “paged” as expected.
That said, when using the base parameter set to ‘%#%’ the hash is supposed to take the correct previous or next page number. This make impossible to use the format and tweak the output if required.
On the contrary, using the ‘%_%’ that force WP to use the format parameter setting the ‘%#%’ as part of the value gets WP to always use the current page everywhere.
So the solution I found was to tweak everything in the base parameter like in the following snippet:
$paginate_links = paginate_links( array(
'base' => preg_replace('/\?.*/', "https://wordpress.stackexchange.com/", get_pagenum_link()) . '%_%',
'prev_text' => __('« Indietro'),
'next_text' => __('Avanti »'),
'mid_size' => 5,
'current' => $current,
'total' => $totalpages
));