限制wp_Query内分页显示的页面数量

时间:2015-05-19 作者:lotech

我有一个如下查询:

$args = array (
    \'post_type\'              => $postType,
    \'paged\'                  => $paged,
    \'pagination\'             => true,
    \'posts_per_page\'         => \'10\',
    \'order\'                  => \'DESC\',
    \'orderby\'                => \'date\',
);

// The Query
$wp_query = new WP_Query( $args );

// The Loop
if ( $wp_query->have_posts() ) {
    while ( $wp_query->have_posts() ) {
        $wp_query->the_post();

            // post stuff

    }
} else { 
    // no posts 
}

pagination($additional_loop->max_num_pages); wp_reset_postdata(); wp_reset_query();
我在函数中也有一些自定义分页。php如下所示:

function pagination($pages = \'\', $range = 4)
{  
     $showitems = ($range * 2)+1;  

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == \'\')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }   

     if(1 != $pages)
     {
         echo "<div class=\\"pagination\\"><span>Page ".$paged." of ".$pages."</span>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href=\'".get_pagenum_link(1)."\'>&laquo; First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href=\'".get_pagenum_link($paged - 1)."\'>&lsaquo; Previous</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\\"current\\">".$i."</span>":"<a href=\'".get_pagenum_link($i)."\' class=\\"inactive\\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\\"".get_pagenum_link($paged + 1)."\\">Next &rsaquo;</a>";  
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href=\'".get_pagenum_link($pages)."\'>Last &raquo;</a>";
         echo "</div>\\n";
     }
}
同样,效果很好。我唯一搞不清楚的是如何限制返回的实际页数。例如,我可能有300篇帖子,分为10页。然而,我只想展示总共30篇文章,分为3页,共10页。

1 个回复
SO网友:shanebp

将查询代码更改为:

add_filter( \'post_limits\', \'my_post_limits\' );

// The Query
$wp_query = new WP_Query( $args );

remove_filter( \'post_limits\', \'my_post_limits\' );
在主题/功能中。php,添加以下内容:

function my_post_limits( $limit, $query ) {

    return \'LIMIT 0, 30\';

}

结束