[WP]カスタム投稿のアーカイブページで「次の年」「前の年」リンクを表示する方法
スポンサード
投稿タイプを指定する場合は、以下の8行目と23行目のように
あとはリンクを出したい箇所に以下の記述
スポンサード
カスタム投稿のアーカイブページで「前の年」「次の年」のリンクを付けようと思っていた所、WordPressの年別アーカイブページで「次の年」「前の年」のリンクを表示する方法の記事でリンクの実装方法が紹介されていましたので参考にさせていただきました。
カスタム投稿の年別アーカイブページに「前の年」「次の年」のリンク
以下のコードをfunctions.php に記述します。投稿タイプを指定する場合は、以下の8行目と23行目のように
'post_type' => ポストタイプ
を追加します。//次の年のリンクを取得 function get_next_year_link() { $this_year = intval( get_the_time( 'Y' ) ); $next_year = $this_year + 1; //次の年に投稿があるか調べる $args = array( 'year' => $next_year, 'post_type' => ポストタイプ, ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { return get_year_link( $next_year ); } } //前の年のリンクを取得 function get_prev_year_link() { $this_year = intval( get_the_time( 'Y' ) ); $prev_year = $this_year - 1; //前の年に投稿があるか調べる $args = array( 'year' => $prev_year, 'post_type' => ポストタイプ, ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { return get_year_link( $prev_year ); } }
あとはリンクを出したい箇所に以下の記述
<?php if( get_next_year_link() ): ?> <a href="<?php echo get_next_year_link(); ?>?post_type=ポストタイプ">次の年</a> <?php endif; ?> 現在の年</a> <?php if( get_prev_year_link() ):?> <a href="<?php echo get_prev_year_link(); ?>?post_type=ポストタイプ">前の年</a> <?php endif; ?>
スポンサード
コメント