Posted at

WP記事一覧でのページネーション

More than 5 years have passed since last update.


WordPressの記事一覧テンプレート内における,ページネーションの実装例

プラグインを使わずに,functions.php内に記述するだけで出力できる.


「前の10件,次の10件」

function pagination( $pages = '', $range = 4 ) {

global $paged;
if ( empty($paged) ) $paged = 1;

if ( $pages == '' ) {
global $wp_query;
$pages = $wp_query->max_num_pages;
if ( !$pages ) $pages = 1;
}

echo "<div class=\"pagination\">";
if ( $paged > 1 )
echo "<a href=\"".get_pagenum_link($paged - 1)."\" class='paginate_button left'>&lsaquo; 前の10件</a>";
else
echo "<span class='paginate_button left'>&lsaquo; 前の10件</span>";
if ( $paged < $pages )
echo "<a href=\"".get_pagenum_link($paged + 1)."\" class='paginate_button right'>次の10件 &rsaquo;</a>";
else
echo "<span class='paginate_button right'>次の10件 &rsaquo;</span>";
echo "</div>\n";
return;
}


「< 1 .. 3 4 5 6 7 .. 9 >」

function pagination( $max_num_pages=0 ) {

// Don't print empty markup if there's only one page.
$max_num_pages = $max_num_pages ? (int)$max_num_pages : $GLOBALS['wp_query']->max_num_pages;
if ( $max_num_pages < 2 ) {
return;
}

$paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
$pagenum_link = html_entity_decode( get_pagenum_link() );
$query_args = array();
$url_parts = explode( '?', $pagenum_link );

if ( isset( $url_parts[1] ) ) {
wp_parse_str( $url_parts[1], $query_args );
}

$pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link );
$pagenum_link = trailingslashit( $pagenum_link ) . '%_%';

$format = $GLOBALS['wp_rewrite']->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
$format .= $GLOBALS['wp_rewrite']->using_permalinks() ? user_trailingslashit( 'page/%#%', 'paged' ) : '?paged=%#%';

// Set up paginated links.
$links = paginate_links( array(
'base' => $pagenum_link,
'format' => $format,
'total' => $max_num_pages,
'current' => $paged,
'mid_size' => 2,
'add_args' => array_map( 'urlencode', $query_args ),
'prev_text' => __( '&lt;' ),
'next_text' => __( '&gt;' ),
) );

if ( $links ) :

?>
<nav class="navigation paging-navigation" role="navigation">
<div class="pagination loop-pagination">
<?php echo $links; ?>
</div><!-- .pagination -->
</nav><!-- .navigation -->
<?php
endif;
}