Tạo phân trang cho WordPress hỗ trợ custom query

Sáu đã từng giới thiệu cách tạo phân trang cho WordPress không cần dùng plugin, tuy nhiên thì code đó vẫn còn một số hạn chế, phân trang chưa hiển thị cho các câu truy vấn tùy chọn. Trong bài viết này Sáu đã nâng cấp code lên và chỉnh sửa lại một vài lỗi, bây giờ bạn có thể dùng trong một vòng lặp của một câu truy vấn bất kỳ. sau-hi-pagination-wordpress Nếu bạn có kiến thức về PHP và WordPress thì càng tốt, tuy nhiên nếu ngược lại thì bạn chỉ cần sao chép code và sử dụng, không cần biết nó được viết như thế nào, chúng ta chỉ chú trọng đến kết quả mà mình đạt được là gì.

if( ! function_exists( 'the_paginate' ) ) :
function the_paginate($args = null) {
    $defaults = array(
        'title'     => 'Pages',
        'query'     => null
    );
    $args = wp_parse_args($args, $defaults);
    extract($args, EXTR_SKIP);
    if(is_404()) {
        return;
    }
    $currentPage = null;
    $totalPage = null;
    if(empty($query)) {
        global $wp_query;
        $query = $wp_query;
    }

    $currentPage = stheme_get_paged();
    $title .= ':';
    $ppp = intval($query->query['posts_per_page']);
    if($ppp < 1) {
        return;
    }
    $totalPage = intval(ceil($query->found_posts / $ppp));
    if($totalPage <= 1) {
        return;
    }
    $paginateResult = '<div id="sPaginate" class="spaginate paginate"><div class="spaginate-inner paginate-inner"><span class="spaginate-title paginate-title">'.$title.'</span>';

    if ($currentPage > 1) {
        $paginateResult .= '<a class="spaginate-prev prev page-item" href="'.get_pagenum_link($currentPage - 1).'">&laquo;</a>';
    }      
    $paginateResult .= the_paginate_list(1, $totalPage, $currentPage);
    if ($currentPage < $totalPage) {
        $paginateResult .= "<a href='" . get_pagenum_link($currentPage + 1) . "' class='spaginate-next next page-item'>&raquo;</a>";
    }
    $paginateResult .= "</div></div>"; 
    echo $paginateResult;
}
endif;

if( ! function_exists( 'stheme_paginate' ) ) :
function stheme_paginate($args = null) {
    the_paginate($args);
}
endif;

if( ! function_exists( 'the_paginate_list' ) ) :
function the_paginate_list($intStart, $totalPage, $currentPage) {
    $pageHidden = '<span class="spaginate-hidden hidden">...</span>';
    $linkResult = "";
    $hiddenBefore = false;
    $hiddenAfter = false;
    for ($i = $intStart; $i <= $totalPage; $i++) {
        if($currentPage === intval($i)) {
            $linkResult .= '<span class="spaginate-current page-item current">'.$i.'</span>';
        }
        else if(($i <= 6 && $currentPage < 10) || $i == $totalPage || $i == 1 || $i < 4 || ($i <= 6 && $totalPage <= 6) || ($i > $currentPage && ($i <= ($currentPage + 2))) || ($i < $currentPage && ($i >= ($currentPage - 2))) || ($i >= ($totalPage - 2) && $i < $totalPage)) {
            $linkResult .= '<a class="spaginate-link page-item" href="'.get_pagenum_link($i).'">'.$i.'</a>';
            if($i <= 6 && $currentPage < 10) {
                $hiddenBefore = true;
            }
        }
        else {
            if(!$hiddenBefore) {
                $linkResult .= $pageHidden;
                $hiddenBefore = true;
            }
            else if(!$hiddenAfter && $i > $currentPage) {
                $linkResult .= $pageHidden;
                $hiddenAfter = true;
            }
        }
    }
    return $linkResult;
}
endif;

function stheme_get_paged() {
    $paged = intval(get_query_var('paged')) ? intval(get_query_var('paged')) : 1;
    return $paged;
}

Bên trên là code PHP mà Sáu đã tạo ra, gom thành các hàm nhỏ cho bạn dễ hiểu và dễ sử dụng lại. Để cho phân trang hiển thị được đẹp hơn thì bạn cần phải bổ sung thêm css:

.spaginate .spaginate-title {
    display: none;
}

.spaginate .spaginate-link, .spaginate .spaginate-current, .spaginate .spaginate-next, .spaginate .spaginate-prev {
    background-color: #E9E9E9;
    border: 1px solid #D2D2D2;
    border-radius: 2px;
    color: #555555;
    display: inline-block;
    font-size: 1em;
    font-weight: 700;
    margin: 0 2px;
    padding: 0.6em 0.8em;
    position: relative;
    text-decoration: none;
}

.spaginate .spaginate-current, .spaginate .spaginate-link:hover, .spaginate .spaginate-next:hover, .spaginate .spaginate-prev:hover {
    background-color: #01B1D3;
    border: 1px solid #01B1D3;
    color: #FFFFFF;
}

.site-paginate {
    display: block;
    margin-top: 20px;
    position: relative;
    text-align: center;
    z-index: 9999;
}

Cách sử dụng rất dễ, bạn chỉ cần gọi hàm stheme_paginate là có thể hiển thị được phân trang, tuy nhiên nếu không có tham số đầu vào thì code này sẽ có tác dụng đối với query chính trên blog của bạn.

<?php $blog = new WP_Query(array('posts_per_page' => 5, 'paged' => stheme_get_paged())); ?>
<div class="list-post">
    <?php if($blog->have_posts()) : ?>
        <?php while($blog->have_posts()) : $blog->the_post(); ?>
            <article id="post-<?php the_ID(); ?>" <?php post_class('blog-posts'); ?> <?php spost_schema(); ?>>
                <header class="article-header entry-header">
                    <?php stheme_template('post', 'title'); ?>
                    <span class="postinfo entry-meta">Đăng bởi <?php spost_author_link(); ?> trong chuyên mục: <?php spost_category(); ?>  vào ngày: <?php echo get_the_date(); ?></span>        
                </header>
                <div class="article-content">
                    <?php stheme_template('post', 'thumbnail'); ?>
                    <span class="artice-preview">
                        <?php the_excerpt(); ?>
                    </span>
                    <div class="clearfix"></div>
                    <div class="read-more">
                        <?php stheme_template('post', 'comment'); ?>
                        <span class="more">
                            <a class="darkbtn" href="<?php the_permalink(); ?>"><span>Xem thêm</span></a>
                        </span>
                    </div>
                </div>                           
            </article>                       
        <?php endwhile; wp_reset_postdata(); ?>
    <?php endif; ?>
</div>
<?php stheme_paginate(array('query' => $blog)); ?>

Như ví dụ bên trên, Sáu có truy vấn tùy chọn là $blog, bây giờ mình muốn tạo phân trang cho các bài viết của truy vấn này, hiển thị mỗi trang là 5 bài viết thì mình sẽ dùng lại hàm phân trang như sau:

<?php stheme_paginate(array('query' => $blog)); ?>

Tuy lần cập nhật này có chỉnh sửa lại đôi chút, nhưng có thể vẫn còn nhiều lỗi trong đó. Các bạn nếu ủng hộ thì hãy sử dụng code này và report lỗi lại giúp mình nhé. Chân thành cảm ơn và chúc bạn thành công.

Rate this post