Archived topic
Adding Pagination to a Custom Page Template
1 reply · Started by Daniel on September 26, 2022
I have a custom page template on my homepage that uses get_query to list pages. I would like to add numbered pagination. Is there a way to add the pagination function within GeneratePress to my custom page? I tried to use the the_posts_pagination function below and it did not work.
Is there any way do do this, or is the function unsupported on custom pages?
<?php /* Template Name: MarketCap */ ?>
// Gets theme header
<?php get_header(); ?>
// Queries for pages and orders results by market cap rank
<?php
global $post;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 0;
$postsPerPage = 100;
$postOffset = $paged * $postsPerPage;
$args_page = array(
'post_type' => 'page',
'offset' => $postOffset,
'posts_per_page' => $postsPerPage,
'meta_key' => 'market_cap_rank',
'orderby' => 'meta_value_num',
'order'=>'ASC'
);
// Shows pages in table format
$postslist = new WP_Query( $args_page ); ?>
<table><thead>
<tr>
<th>Rank </th>
<th>Company</th>
<th>Market Cap (USD)</th>
</tr>
</thead>
<?php if ( $postslist->have_posts() ) :
while ( $postslist->have_posts() ) : $postslist->the_post(); ?>
<tbody>
<tr>
<td><?php the_field('market_cap_rank'); ?></td>
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?> </a> </td>
<td>$<?php the_field('market_cap_usd_trillion'); ?></td>
// Menu page links
<?php endwhile;
the_posts_pagination( array(
'end_size' => 2,
'mid_size' => apply_filters( 'generate_pagination_mid_size', 1 ),
'prev_text' => apply_filters( 'generate_previous_link_text', __( '← Previous', 'generatepress' ) ),
'next_text' => apply_filters( 'generate_next_link_text', __( 'Next →', 'generatepress' ) ),
) );
wp_reset_postdata();
endif;
?>
</tr></tbody></table>
// <?php wp_pagenavi( array( 'query' => $q ) );
//wp_reset_postdata();
// endif;
//?>
<?php
/**
* generate_after_primary_content_area hook.
*
* @since 2.0
*/
do_action( 'generate_after_primary_content_area' );
generate_construct_sidebars();
get_footer();
?>
Thank you very much!
Hi Daniel,
For reference, this is how that's function is called in GP: https://github.com/tomusborne/generatepress/blob/adfe090929b0515cdf894f4c6b722cfe8c0790dc/inc/structure/post-meta.php#:~:text=%27the_posts_pagination%27%20)%20)%20%7B-,the_posts_pagination(,-array(
You can also try adding do_action( 'generate_paging_navigation' );, then create a Block Element - Post Navigation: https://docs.generatepress.com/article/block-element-post-navigation/
Here's another alternative: https://developer.wordpress.org/reference/functions/the_posts_pagination/