【问题标题】:Wordpress pagination with get_posts使用 get_posts 进行 Wordpress 分页
【发布时间】:2017-04-14 22:41:46
【问题描述】:

对于如何在 wordpress 中为自定义循环添加分页,我找不到明确的答案。根据我从 codex 的理解,我应该使用 get_posts() (或者我错了,我应该使用 WP_Query 或 query_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. 它从数据库中获取帖子两次只是为了计算它们。 有没有一种功能可以让我在不查询组合分类法的情况下检查帖子的数量?

我是否正确地解决了这个问题?如果没有,最好的选择是什么?

【问题讨论】:

    标签: php wordpress pagination


    【解决方案1】:

    比在 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; ?>
    

    【讨论】:

    • 我不明白 wp-pagenavi 可以如何帮助我。从我看到你的代码和我的类似。您使用了 WP_Query,所以我将首先检查它是否可以简化我的代码。
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2016-06-17
    • 1970-01-01
    • 2015-04-11
    相关资源
    最近更新 更多