簡體   English   中英

使用 get_posts 進行 Wordpress 分頁

[英]Wordpress pagination with get_posts

我找不到關於如何在 wordpress 中為自定義循環添加分頁的明確答案。 根據我從 codex 中的理解,我應該使用 get_posts() (或者我錯了,我應該使用 WP_Query 或 query_posts?)

假設我有一個自定義帖子類型entry寬度分類法entry_cat ,我想顯示類別為cat-1cat-2 entry並添加分頁。

我的代碼主要工作:

<?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. 它從數據庫中獲取帖子兩次只是為了計算它們。 是否有一個功能可以讓我檢查分類組合中的帖子數量而不查詢它們?

我什至正確地解決了這個問題嗎? 如果沒有,最好的選擇是什么?

比在 WordPress 中使用 wp-pagenavi 插件和自定義查詢更好,例如這個帶有 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; ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM