[WordPress] 前の記事、次の記事へのリンクの表示非表示がうまく効かない場合
single.phpで「前の記事」「次の記事」を設置するのに、もし、該当リンクがない場合にリンク表示を無くしたい、という場合にどう記述するか、検索するとよくヒットするのが
1 2 3 4 5 6 |
<?php if (get_next_post()):?> <div class="next"><?php next_post_link('%link','< 前の記事へ',true); ?></div> <?php endif; ?> <?php if (get_previous_post()):?> <div class="prev"><?php previous_post_link('%link','次の記事へ >',true); ?></div> <?php endif; ?> |
のような記述で、get_next_post()、get_previous_post()で次の記事があるかないかを調べ、あればnext_post_link()、previous_post_link()でリンクを出力する、という仕組みです。
ただ、該当記事がカテゴリ内にあり、next_post_link()、previous_post_link()の第3引数でtrueを指定している場合、get_next_post()、get_previous_post()の次の記事の判別がうまくいかない場合があります。
具体的には次の記事がないのに要素だけ出力されてしまう場合があり困っていたのですが、get_next_post()、get_previous_post()にも「同じカテゴリ内で」の条件を付けると良いようです。
具体的には
1 2 3 4 5 6 |
<?php if (get_next_post(true)):?> <div class="next"><?php next_post_link('%link','< 前の記事へ',true); ?></div> <?php endif; ?> <?php if (get_previous_post(true)):?> <div class="prev"><?php previous_post_link('%link','次の記事へ >',true); ?></div> <?php endif; ?> |
で解決しました。
具体的にどういう場合に記事の判別がうまくいかないのか原因がよくわからず調査中です。