I have created a class that creates a custom endpoint
for WooCommerce My Account and on this endpoint I am trying to add the lists of products with pagination using WP_Query
.
Here is the code:
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'paged' => $paged
);
$query = new \WP_Query( $args );
while( $query->have_posts() ):
$query->the_post();
echo get_the_title().'<br>';
endwhile;
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
The pagination links appear just fine and the correct number of page links.
The problem is that the get_query_var('paged') is always 0.
I checked using var_dump get_query_var('paged')
. I am guessing that it has something to do with the fact that I am creating the WP_Query instance on an endpoint.
Anyone have any ideas if WP_Query
with pagination can work on a custom endpoint?
CodePudding user response:
"the problem is that the get_query_var('paged') is always 0"
According to the documentation, when you're using a custom template, the query_var
should be page
NOT paged
.
Replace this line:
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
With this one:
$paged = get_query_var( 'page', 1);
Also it's a good practice to use wp_reset_postdata
Docs function after you're done with your query!
CodePudding user response:
After getting some good sleep, I came back to this issue this morning and with fresh eyes and I could see what was causing the issue.
As this was a custom endpoint point the 'paged
' variable was being added to the custom endpoint query variable, in this case called 'listings'.
If I var_dump
the listings
query variable I get page/2
etc. So I wrote
if( empty( get_query_var('listings') ) ):
$paged = 1;
else:
$paged_array = explode('/',get_query_var('listings'));
$paged = $paged_array[1];
endif;
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'paged' => $paged
);
This allowed me to get a paged variable and now the pagination works.
Seems like a bit of a hack, but not sure how else to get a paged variable from an endpoint