WordPress函数next_posts_link()获取下一页链接

描述:

显示同分类“下一页”分页的链接

用法:

 <?php next_posts_link( $label , $max_pages ); ?> 

参数:

$label

(string) (可选) 链接文本。

默认值: ‘Next Page »’

$max_pages

(integer) (可选) 限制显示链接的页数。默认值“0”表示“无限制”。

默认值: 0

示例:

默认用法

<?php next_posts_link(); ?>

使用实例

<?php next_posts_link( '下一页 »', 0 ); ?>

使用WP_Query查询循环时的用法
使用WP_Query查询循环时,将$max_pages参数添加到next_posts_link()函数。要获取总页数,可以使用自定义WP_查询对象的“max_num_pages”属性。

<?php
// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

// the query
$the_query = new WP_Query( 'cat=1&paged=' . $paged ); 
?>

<?php if ( $the_query->have_posts() ) : ?>

<?php
// the loop
while ( $the_query->have_posts() ) : $the_query->the_post(); 
?>
<?php the_title(); ?>
<?php endwhile; ?>

<?php

// next_posts_link() usage with max_num_pages
next_posts_link( 'Older Entries', $the_query->max_num_pages );
previous_posts_link( 'Newer Entries' );
?>

<?php 
// clean up after the query and pagination
wp_reset_postdata(); 
?>

<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

源文件:

/**
 * Display the next posts page link.
 *
 * @since 0.71
 *
 * @param string $label    Content for link text.
 * @param int    $max_page Optional. Max pages.
 */
function next_posts_link( $label = null, $max_page = 0 ) {
	echo get_next_posts_link( $label, $max_page );
}