wordpress知识库
网站首页 > 知识库 > wordpress知识 >

wordpress自定义分页代码

2014/08/20

如果想要自定义分页代码以满足特定需求,可以使用wordpress插件提供的paginate_links()函数或编写自己的分页函数。

以下是一个示例自定义分页代码的示例,该代码使用自定义函数来生成分页链接:

function custom_pagination( $total_pages, $current_page ) {
    $prev_text = '« Previous';
    $next_text = 'Next »';

    echo '<div class="pagination">';

    if ( $current_page > 1 ) {
        echo '<a href="' . get_pagenum_link( $current_page - 1 ) . '">' . $prev_text . '</a>';
    }

    for ( $i = 1; $i <= $total_pages; $i++ ) {
        if ( $i == $current_page ) {
            echo '<span class="current">' . $i . '</span>';
        } else {
            echo '<a href="' . get_pagenum_link( $i ) . '">' . $i . '</a>';
        }
    }

    if ( $current_page < $total_pages ) {
        echo '<a href="' . get_pagenum_link( $current_page + 1 ) . '">' . $next_text . '</a>';
    }

    echo '</div>';
}

上述示例代码中,我们定义了一个名为custom_pagination()的自定义函数。该函数接受两个参数:总页数和当前页数。通过循环生成分页链接,并根据当前页进行样式设置。

要在模板文件中使用这个自定义分页代码,可以调用custom_pagination()函数并传递总页数和当前页数作为参数,如下所示:

$total_pages = 10;
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

custom_pagination( $total_pages, $current_page );