Skip to content

Instantly share code, notes, and snippets.

@astockwell
Last active December 21, 2015 00:59
Show Gist options
  • Save astockwell/6224123 to your computer and use it in GitHub Desktop.
Save astockwell/6224123 to your computer and use it in GitHub Desktop.
Paginate a custom WP_Query on a Wordpress static page. Be sure to REFRESH PERMALINKS!!!
// add new rule to match routes at "/events/page/#"
function add_rewrite_rules($aRules) {
$aNewRules = array('events/page/(\d+)/?$' => 'index.php?pagename=events&paged=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');
...content...
<?php
$args = array(
'posts_per_page' => $wp_query->query_vars['posts_per_page'],
'offset' => $wp_query->query_vars['paged'] * $wp_query->query_vars['posts_per_page'],
'post_type' => 'event',
'order' => 'ASC',
'orderby' => 'menu_order'
);
$my_query = new WP_Query( $args );
if($my_query->have_posts()):
while($my_query->have_posts()): $my_query->the_post(); ?>
<li>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
</li>
<?php endwhile; // End while $my_query->have_posts
endif; // End if $my_query->have_posts
wp_reset_postdata(); ?>
...content...
<div class="pagination-event">
<?php $args = array(
'base' => get_bloginfo('url') . '/events/%_%', //matches page slug
'format' => 'page/%#%/', //url format is "/events/page/#"
'total' => $wp_query->max_num_pages,
'current' => max( 1, $wp_query->query_vars['paged'] ),
'show_all' => true,
//'end_size' => 1,
//'mid_size' => 2,
'prev_next' => True,
'prev_text' => __('&larr; Previous'),
'next_text' => __('Next &rarr;'),
'type' => 'plain',
'add_args' => False,
'add_fragment' => ''
);
echo paginate_links( $args ); ?>
</div>
...content...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment