如果您希望使用凉爽的数字而不是默认的下一个和上一个文章为您的WordPress主题的分页支持,您可以使用著名的PageNavi插件来实现,但是,我更喜欢将分页手动添加到主题中,这样人们就不会 必须去寻找插件。
幸运的是,WordPress 2.1中新增了一个名为“ paginate_links”的强大功能,可让您为网站上的任何查询创建分页样式导航。 这是一个快速教程,用于为您的主题添加简单的页面导航。
分页函数
只需在functions.php文件(或主题中要保留它的任何文件)末尾添加以下代码。
// 数字分页
if ( !function_exists( 'ie_pagination' ) ) {
function ie_pagination() {
$prev_arrow = is_rtl() ? '→' : '←';
$next_arrow = is_rtl() ? '←' : '→';
global $wp_query;
$total = $wp_query->max_num_pages;
$big = 999999999; // need an unlikely integer
if( $total > 1 ) {
if( !$current_page = get_query_var('paged') )
$current_page = 1;
if( get_option('permalink_structure') ) {
$format = 'page/%#%/';
} else {
$format = '&paged=%#%';
}
echo paginate_links(array(
'base'=> str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format'=> $format,
'current'=> max( 1, get_query_var('paged') ),
'total' => $total,
'mid_size'=> 3,
'type' => 'list',
'prev_text'=> $prev_arrow,
'next_text'=> $next_arrow,
) );
}
}
}注意。您还可以参考这里获得更多参数:https://codex.wordpress.org/Function_Reference/paginate_links
分页样式
复制以下CSS并将其粘贴到style.css文件中。
ul.page-numbers {
list-style: none;
margin: 0;
}
.page-numbers:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
ul.page-numbers li {
display: block;
float: left;
margin: 0 4px 4px 0;
text-align: center;
}
.page-numbers a,
.page-numbers span {
line-height: 1.6em;
display: block;
padding: 0 6px;
height: 18px;
line-height: 18px;
font-size: 12px;
text-decoration: none;
font-weight: 400;
cursor: pointer;
border: 1px solid #ddd;
color: #888;
}
.page-numbers a span { padding: 0 }
.page-numbers a:hover,
.page-numbers.current,
.page-numbers.current:hover {
color: #000;
background: #f7f7f7;
text-decoration: none;
}
.page-numbers:hover { text-decoration: none }向主题添加调用分页功能非常简单。 您所要做的就是将以下代码添加到您想要显示任何分页的主题文件中。 最常见的是您的index.php,home.php,category.php,tags.php,archive.php和search.php。 但是,如果您有任何具有分页支持的自定义页面模板,则需要在此处添加它们。
将默认分页替换为以下内容(通常位于endif之后的某个位置):
<?php ie_pagination(); ?>
高级应用
如果您使用WP_Query创建自定义查询,则除非您在$wp_query变量中定义了查询(否则,请勿这样做),否则该功能将无法使用。 要解决此问题,我通常会创建类似以下的新查询:
$wpie_query = new WP_Query( $args );
这样,我可以更改主分页功能以在创建分页时查找变量,例如(编辑第一个代码段):
global $wp_query, $wpie_query;
if ( $wpie_query ) {
$total = $wpie_query->max_num_pages;
} else {
$total = $wp_query->max_num_pages;
}
- 提示:这篇文章发布于 2019/10/19,作者 99839,总计 2072 字.
- 原文: 如何向您的WordPress主题添加分页 | 爱壹主题

























