個別記事ページにサムネイル付きページャー(ページネーション)を作る

今回は、個別記事内ページャー(ページネーション)にアイキャッチ画像のサムネイルを付ける方法を紹介します。
get_adjacent_post()」を使用すると、前後の記事の情報を取得できますので、前後の記事の「ID」を取得します。

get_adjacent_post()

get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy )

$in_same_term … 同じタクソノミー内で移動するかどうか(初期値:false)。
$excluded_terms … 除外するタクソノミーのID。
$previous … 前の投稿を取得するかどうか(初期値:true)。「ture」で前の投稿、「false」で次の投稿を取得。
$taxonomy … 「$in_same_term」が「ture」のときどのタクソノミーにするかを指定。

取得できる情報は下記の通りです。

WP_Post Object
(
    [ID] => 1
    [post_author] => 1
    [post_date] => 2022-02-05 09:00:00
    [post_date_gmt] => 2022-02-05 00:00:00
    [post_content] => WordPress へようこそ。こちらは最初の投稿です。編集または削除し、コンテンツ作成を始めてください。
    [post_title] => Hello world!
    [post_excerpt] => 
    [post_status] => publish
    [comment_status] => open
    [ping_status] => open
    [post_password] => 
    [post_name] => hello-world
    [to_ping] => 
    [pinged] => 
    [post_modified] => 2022-02-05 09:00:00
    [post_modified_gmt] => 2022-02-05 00:00:00
    [post_content_filtered] => 
    [post_parent] => 0
    [guid] => https://www.bossraku.com/?p=1
    [menu_order] => 0
    [post_type] => post
    [post_mime_type] => 
    [comment_count] => 1
    [filter] => raw
)

ページャー(ページネーション) を設置

前後の記事の情報をそれぞれ取得して、「ID」を調べます。
今回はカテゴリをまたいで移動するページャーにしてみました。
ですので、1つ目の引数は「false」にしてあります。
後は「get_permalink()」「get_the_title()」「get_the_post_thumbnail()」を使ってリンクやタイトルを取得していきます。

$prevpost = get_adjacent_post(false, '', true); //前の記事を取得
$nextpost = get_adjacent_post(fasle, '', false); //次の記事を取得
if($prevpost or $nextpost):
	echo '<ul>';
	if($prevpost)://前の記事があったら
		echo '<li><a href="'.get_permalink($prevpost->ID).'">';
		if(get_the_post_thumbnail($prevpost->ID)):
			echo get_the_post_thumbnail($prevpost->ID, 'thumbnail', array('alt'=>get_the_title($prevpost->ID) ));
		else:
			echo '<img src="代替え画像のURL" alt="'.get_the_title($prevpost->ID).'">';
		endif;
		echo get_the_title($prevpost->ID);
		echo '</a></li>';
	endif;
	if($nextpost)://次の記事があったら
		echo '<li><a href="'.get_permalink($nextpost->ID).'">';
		if(get_the_post_thumbnail($nextpost->ID)):
			echo get_the_post_thumbnail($nextpost->ID, 'thumbnail', array('alt'=>get_the_title($nextpost->ID) ));
		else:
			echo '<img src="代替え画像のURL" alt="'.get_the_title($nextpost->ID).'">';
		endif;
		echo get_the_title($nextpost->ID);
		echo '</a></li>';
	endif;
	echo '</ul>';
endif;

ここではリンクの内容を「get_permalink()」、投稿のタイトルを「get_the_title()」で取得しましたが、せっかく「get_adjacent_post()」で情報を取得したのだから、「$prevpost->guid」「$prevpost->post_title」を使ってもよいかもしれません。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です