WordPress主题开发:WP_Query使用分页实例

functions.php加入

<?php 
function lingfeng_custom_pagenavi( $custom_query,$range = 4 ) {
    global $paged,$wp_query;
    if ( !$max_page ) {
        $max_page = $custom_query->max_num_pages;
    }
    if( $max_page >1 ) {
        echo "<div class='fenye'>"; 
        if( !$paged ){
            $paged = 1;
        }
        if( $paged != 1 ) {
            echo "<a href='".get_pagenum_link(1) ."' class='extend' title='跳转到首页'>首页</a>";
        }
        previous_posts_link('上一页');
        if ( $max_page >$range ) {
            if( $paged <$range ) {
                for( $i = 1; $i <= ($range +1); $i++ ) {
                    echo "<a href='".get_pagenum_link($i) ."'";
                if($i==$paged) echo " class='current'";echo ">$i</a>";
                }
            }elseif($paged >= ($max_page -ceil(($range/2)))){
                for($i = $max_page -$range;$i <= $max_page;$i++){
                    echo "<a href='".get_pagenum_link($i) ."'";
                    if($i==$paged)echo " class='current'";echo ">$i</a>";
                    }
                }elseif($paged >= $range &&$paged <($max_page -ceil(($range/2)))){
                    for($i = ($paged -ceil($range/2));$i <= ($paged +ceil(($range/2)));$i++){
                        echo "<a href='".get_pagenum_link($i) ."'";if($i==$paged) echo " class='current'";echo ">$i</a>";
                    }
                }
            }else{
                for($i = 1;$i <= $max_page;$i++){
                    echo "<a href='".get_pagenum_link($i) ."'";
                    if($i==$paged)echo " class='current'";echo ">$i</a>";
                }
            }
        next_posts_link('下一页');
        if($paged != $max_page){
            echo "<a href='".get_pagenum_link($max_page) ."' class='extend' title='跳转到最后一页'>尾页</a>";
        }
        echo '<span>共['.$max_page.']页</span>';
        echo "</div>\n";  
    }
}
 ?>

调用分页:

<?php
 // 1.用于查询的参数或者参数集合
$args = array(
  'post_type'=>'post',
  'posts_per_page'=>3,
  'paged'=>get_query_var('paged')
);

// 2.查询
$myquery=new WP_Query($args);

// 3.判断查询的结果,有内容则循环
if($myquery->have_posts()):while($myquery->have_posts()):$myquery->the_post();
?>

//数据

<?php 
endwhile;
endif;
//调用分页
lingfeng_custom_pagenavi($myquery);
// 4.重置请求数据
wp_reset_postdata();
?>

 

注意:当WP_Query中包含offset时,分页功能就失效了。

posted @ 2017-02-16 23:46  tinyphp  Views(3697)  Comments(1Edit  收藏  举报