目次
はじめに
とある事情でget_postsでページングしなければならない。
てなわけで、作ってみました。
ソースコード
function.php
function get_pagination($max_pages = '', $post_type = 'post', $range = 2)
{
$showitems = ($range )+1;
global $paged;
if(empty($paged))
$paged = 1;
if(empty($max_pages))
$max_pages = 1;
if(1 != $max_pages)
{
echo "<div class='pagination'>";
// 最初に
if($paged > 2 && $paged > $range+1 && $showitems < $max_pages)
{
echo "<a href='".get_pagenum_link(1)."'>«</a>";
}
// 前に
if($paged > 1 && $showitems < $max_pages)
{
echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
}
// 連番
for ($i=1; $i <= $max_pages; $i++)
{
if (1 != $max_pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $max_pages <= $showitems ))
{
echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
}
}
// 次に
if ($paged < $max_pages && $showitems < $max_pages)
{
echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
}
// 最後に
if ($paged < $max_pages-1 && $paged+$range-1 < $max_pages && $showitems < $max_pages)
{
echo "<a href='".get_pagenum_link($max_pages)."'>»</a>";
}
echo "</div>n";
}
}
テーマファイル
// ポストタイプを選択
$post_type = get_post_type();
// 記事のはきだし
$page = $paged != 0 ?($paged-1)*20:0;
if( $posts = get_posts( 'post_type='.$post_type.'&orderyby=date&numberposts=20&cat_name=n_r&offset='.$page))
{
foreach($posts as $post)
{
the_contents()
}
}
// ページングの表示
get_pagination(ceil(count(get_posts( 'post_type='.$post_type.'&numberposts=-1' ))/20), $post_type);
CSS
.pagination {
clear:both;
padding:20px 0;
position:relative;
font-size:11px;
line-height:13px;
}
.pagination span, .pagination a {
display:block;
float:left;
margin: 2px 2px 2px 0;
padding:6px 9px 5px 9px;
text-decoration:none;
width:auto;
color:#fff;
background: #555;
}
.pagination a:hover{
color:#fff;
background: #3279BB;
}
.pagination .current{
padding:6px 9px 5px 9px;
background: #3279BB;
color:#fff;
}
$post_type にポストのタイプをセットして、ページネーションしたいところに下のを設置。
get_pagination(ceil(count(get_posts( 'post_type='.$post_type.'&numberposts=-1' ))/20), $post_type);
結構、無理やり作っている感があるので、ご利用は計画的に・・・
ではノシ