Can a WordPress expert confirm – is there a simple, elegant, WordPress-native way in which get_posts() queries can be paginated? I have tried to piece together how to do it from various posts, but can’t seem to get it to work.
I often use get_posts() for querying my Custom Post types – but if I can’t easily paginate these I may just drop get_posts() and get into the habit of using wp_query() for Custom POst Types.
What is wrong with my code? I have struggled through many PHP problems, but would still consider myself a novice.
Trying for the simplest clearest option here so I can understand how it works, use it as a template for future projects.
<div class="content-primary">
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query_args = array(
'post_type' => 'project',
'posts_per_page' => 10,
'paged' => $paged
);
$query_custom_posts = get_posts( $query_args );
foreach ( $query_custom_posts as $post ) : setup_postdata( $post ); ?>
<article>
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) : the_post_thumbnail( 'thumbnail' ); endif;?>
<h3><?php the_title(); ?></h3>
</a>
<div><?php the_date(); ?></div>
<div><?php the_excerpt(); ?></div>
</article>
<?php endforeach; ?>
<?php
global $query_args;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $query_args->max_num_pages
) );
?>
<?php wp_reset_postdata();?>
</div>
I really hoped this would work, though I am aware of errors in it – I know my $query_args contains no max_num_pages.
Would be nice to have the optional use of the WordPress next_posts_link() / previous_posts_link() too, rather than paginate_links(), but not sure if this can be made to work with get_posts().
You simply need to add the following line:
just before your get_posts() loop starts.
Full article here: http://blog.onireon.it/wordpress-get_posts-and-pagination-posts-are-correctly-displayed-but-no-pagination-links-are-showing/