John Davidson

php - WP_Query pagination on a custom endpoint in WooCommerce

0 comments
Message:


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?



My Answer:
'product',_ 'posts_per_page' => 10,_ 'paged' => $paged,_ );_ _$query = new WP_Query( $args );_ _if ( $query->have_posts() ) {_ while ( $query->have_posts() ) {_ $query->the_post();_ // Display product information here_ }_ _// Pagination_ echo paginate_links( array(_ 'total' => $query->max_num_pages,_ ) );_ }_ _wp_reset_postdata();_ }_}_add_action( 'woocommerce_account_custom_endpoint', 'custom_endpoint_content' );_?>_However, when I try to access the custom endpoint, the pagination links do not appear and all products are displayed on a single page. What am I doing wrong and how can I fix this issue?

Rate this post

3 of 5 based on 1820 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us