WordPress函数get_next_posts_link()

描述:

调用同分类“下一页”分页的链接

用法:

 <?php echo get_next_posts_link( $label, $max_page ); ?>

参数:

$label

(string) (可选) 链接文本的内容

默认值: Next Page »

$max_page

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

默认值: 0

示例:

默认用法

<?php echo get_next_posts_link(); ?>

自定义标签

<?php echo get_next_posts_link('Go to next page'); ?>

自定义标签和自定义页数

<?php echo get_next_posts_link('Go to next page',4); ?>

使用WP_Query查询循环时的用法
使用WP_Query查询循环时,将$max_pages参数添加到get_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

// get_next_posts_link() usage with max_num_pages
echo get_next_posts_link( 'Older Entries', $the_query->max_num_pages );
echo get_previous_posts_link( 'Newer Entries' );
?>

<?php 
// clean up after our query
wp_reset_postdata(); 
?>

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

源文件:

/**
 * Return the next posts page link.
 *
 * @since 2.7.0
 *
 * @global int      $paged
 * @global WP_Query $wp_query
 *
 * @param string $label    Content for link text.
 * @param int    $max_page Optional. Max pages.
 * @return string|void HTML-formatted next posts page link.
 */
function get_next_posts_link( $label = null, $max_page = 0 ) {
	global $paged, $wp_query;

	if ( !$max_page )
		$max_page = $wp_query->max_num_pages;

	if ( !$paged )
		$paged = 1;

	$nextpage = intval($paged) + 1;

	if ( null === $label )
		$label = __( 'Next Page »' );

	if ( !is_single() && ( $nextpage <= $max_page="" )="" )="" {="" *="" *="" filter="" the="" anchor="" tag="" attributes="" for="" the="" next="" posts="" page="" link.="" *="" *="" @since="" 2.7.0="" *="" *="" @param="" string="" $attributes="" attributes="" for="" the="" anchor="" tag.="" */="" $attr="apply_filters(" 'next_posts_link_attributes',="" ''="" );="" return="">" . preg_replace('/&([^#])(?![a-z]{1,8};)/i', '&$1', $label) . '';
	}
}