wordpress 自定义分页代码

wordpress 自定义分页代码


<?php
get_header();
?>
 
<?php
$args = array(
    'cat' => $cat,
    'paged' => $paged,
    'posts_per_page' => 2,
);
 
$wp_query = new WP_Query($args);
 
if ($wp_query->have_posts()):
    while ($wp_query->have_posts()):$wp_query->the_post();
        the_title('<li>','</li>');
    endwhile;
endif;
mo_paging();
wp_reset_postdata();
?>
 
<?php
get_footer();
————————————————
版权声明:本文为CSDN博主「李 书 明」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lsmxx/article/details/104494718/

上面代码要加入wp_reset_postdata(); 不加上这段会出现分页重复问题

function.php文件中加入以下代码,

function mo_paging() {
    $p = 3;
    if ( is_singular() ) return;
    global $wp_query, $paged;
    $max_page = $wp_query->max_num_pages;
    if ( $max_page == 1 ) return;
    echo '<div class="pagination"><ul>';
    if ( empty( $paged ) ) $paged = 1;
    echo '<li class="prev-page">'; previous_posts_link('上一页'); echo '</li>';
    if ( $paged > $p + 1 ) _paging_link( 1, '<li>第一页</li>' );
    if ( $paged > $p + 2 ) echo "<li><span>···</span></li>";
    for( $i = $paged - $p; $i <= $paged + $p; $i++ ) {
        if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<li class=\"active\"><span>{$i}</span></li>" : _paging_link( $i );
    }
    if ( $paged < $max_page - $p - 1 ) echo "<li><span> ... </span></li>";
    echo '<li class="next-page">'; next_posts_link('下一页'); echo '</li>';
    echo '<li><span>共 '.$max_page.' 页</span></li>';
    echo '</ul></div>';
}
 
function _paging_link( $i, $title = '' ) {
    if ( $title == '' ) $title = "第 {$i} 页";
    echo "<li><a href='", esc_html( get_pagenum_link( $i ) ), "'>{$i}</a></li>";
}

修改下代码

<?php
$args = array(
    'cat' => $cat,
    'paged' => $paged,
    'posts_per_page' => 6,//指定每页数量
); $wp_query = new WP_Query($args); ?>				
<?php if ($wp_query->have_posts()): while ($wp_query->have_posts()):$wp_query->the_post(); ?>	
//html代码
<?php 嵌入代码 ?>
//html代码
<?php endwhile; endif;?> 

//html代码,下面的代码不用嵌套进上面的循环
<?php mo_paging();?> 
<?php wp_reset_postdata();?>
QR:wordpress 自定义分页代码