2016-11-30 183 views
1

我无法找到一个明确的答案,我应该如何将分页添加到WordPress中的自定义循环。从我法典明白我应该使用get_posts()(或我错了,我应该使用WP_Query或query_posts?)WordPress的分页与get_posts

可以说我有一个自定义后类型entry宽度分类entry_cat,我想展示类别为cat-1cat-2,并添加分页。

我的代码大多工作原理:

<?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), 
)); 
?> 

,但我与它的两个问题。

  1. 它不能用于首页。
  2. 它从数据库中获取两次帖子来计算它们。 是否有一个函数允许我检查分类组合中的帖子数而不查询它们?

我是否正确接近问题?如果不是,最好的选择是什么?

回答

0
比使用WP-pagenavi插件和自定义查询在WordPress例如本万阿英,蒋达清与WP-pagenavi插件更好

<?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; ?> 
+0

我没有看到WP-pagenavi如何能帮助我。从我看到你的代码与我的相似。您使用了WP_Query,因此我将首先检查它是否可以简化我的代码。 –