WordPressのsingle.phpで、次の記事、前の記事を取得する方法を紹介してきます。
テーマのカスタマイズやオリジナルテーマを作成する時には必須なので是非確認しておこう。
single.phpで前後のタイトルとリンクを別々に取得する方法
では早速、WordPressのsingle.phpで次の記事と前の記事の情報を取得していきましょう。
基本的には、下記で取得できちゃいます。
<?php previous_post_link(); ?> //前の記事 <?php next_post_link(); ?> //次の記事
ただこれだけでは、ちょっとデザインが変わると対応が難しいですよね。
なので、リンクと前の記事、次の記事のタイトルを別々に取得します。
前の記事のリンクを取得
まずは、前の記事のリンクを文字列のして取得してみます。
<?php $prevpost = get_previous_post(); if( !empty( $prevpost ) ) { $prevurl = get_permalink( $prevpost->ID ); } echo $prevurl; //URL出力 ?>
こんな感じ。
これで、前の記事のリンクだけを取得することができます。
これにタイトルも同時に取得してみましょう。
<?php $prevpost = get_previous_post(); if( !empty( $prevpost ) ) { $prevurl = get_permalink( $prevpost->ID ); $prevttl = get_the_title( $prev_post->ID ); } echo $prevurl; //URL出力 echo $prevttl; //タイトル出力 ?>
次の記事のリンクを取得
続いて次の記事のリンクを文字列のして取得します。
<?php $nextpost = get_next_post(); if( !empty( $nextpost ) ) { $nexturl = get_permalink( $nextpost->ID ); } echo $nexturl; //URL出力 ?>
こちらもタイトルも同時に取得してみましょう。
<?php $nextpost = get_next_post(); if( !empty( $nextpost ) ) { $nexturl = get_permalink( $nextpost->ID ); $nextttl = get_the_title( $next_post->ID ); } echo $nexturl; //URL出力 echo $nextttl; //タイトル出力 ?>
こんな感じ!
「Intuitive Custom Post Order」を併せて使う際の注意
記事を自由に並び換えできる「Intuitive Custom Post Order」と併せて使う場合に上記の方法は注意してください。
プラグイン「Intuitive Custom Post Order」と併せて使用してしまうとリンクとタイトルがめちゃくちゃな順番になってしまいます。
解決方法は調査中ですが、多分記事投稿順で取得してそう・・・?
なぜかリンク先がおかしい・・・となったら「Intuitive Custom Post Order」の可能性があるので確認してみましょう。
コメント