Bartek Suski
Bartek Suski

Reputation: 161

Wordpress pagination with get_posts

I couldn't find a definite answer to how I should add pagination to custom loops in wordpress. From what I understood from codex I'm supposed to use get_posts() (or am I wrong and I should use WP_Query or query_posts?)

Lets say I have a custom post type entry width taxonomy entry_cat and I want to display ones with category cat-1 or cat-2 and add pagination.

My code mostly works:

<?php
$pageda = get_query_var('paged') ? get_query_var('paged') : 1;
$posts_per_page = get_option('posts_per_page');
$post_offset = ($pageda - 1) * $posts_per_page;
$args = array(
    'numberposts'   =>  $posts_per_page,
    'post_type'     =>  'entry',
    'offset'        =>  $post_offset,
    'tax_query'     =>  array(
        'relation'  =>  'OR',
        array(
            'taxonomy'  =>  'entry_cat',
            'field'     =>  'slug',
            'terms'     =>  'cat-1',
        ),
        array(
            'taxonomy'  =>  'entry_cat',
            'field'     =>  'slug',
            'terms'     =>  'cat-2',
        ),
    ),
);
$posts=get_posts($args);
$args['numberposts'] = -1;
$posts_count=count(get_posts($args));
if($posts):
foreach($posts as $post):
?>
    <?php the_title() ?><br />
<?php 
endforeach;
endif;
echo paginate_links(array(
    'current'   =>  $pageda,
    'total'     =>  ceil($posts_count / $posts_per_page),
));
?>

but I have two issues with it.

  1. It cannot be used of front page.
  2. It gets posts from the database twice just to count them. Is there a function that allows me to check for the number of posts within a combination of taxonomies without querying them?

Am I even approaching the problem correctly? If not, what would be the best option?

Upvotes: 1

Views: 2234

Answers (1)

hasan movahed
hasan movahed

Reputation: 364

better than using wp-pagenavi plugins and custom query in WordPress for example this probelm with wp-pagenavi plugins :

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$myquery = new WP_Query(
    array(
        'posts_per_page' => '2',
        'paged'=>$paged
        // add any other parameters to your wp_query array
    )   
);  
?>

<?php
if ($myquery->have_posts()) :  while ($myquery->have_posts()) : $myquery->the_post();
?>

<!-- Start your post. Below an example: -->

<div class="article-box">                               
<h2 class="article-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="article-excerpt"><?php echo(get_the_excerpt()); ?></p>                        
</div>

<!-- End of your post -->

<?php endwhile; ?>
<?php wp_pagenavi( array( 'query' => $myquery ) ); ?><!-- IMPORTANT: make sure to include an array with your previously declared query values in here -->
<?php wp_reset_query(); ?>
<?php else : ?>
<p>No posts found</p>
<?php endif; ?>

Upvotes: 1

Related Questions