2016-11-30 48 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,因此我將首先檢查它是否可以簡化我的代碼。 –