【WordPress】アーカイブ(記事一覧)ではなく「最新の個別記事」へ直接リンクさせる方法(2種類)

「記事一覧」は必要なく、すぐに最近記事を出したいときがたまにあります
ずいぶん前に いろんなサイトやブログから必死にコピペ編集したコードを、このたびGeminiに整えてもらいました

1.アーカイブURLへのアクセスをに最新投稿に強制リダイレクト

アーカイブぺージURL(カスタム投稿「news」だったら/news/ など)にアクセスしたときに301リダイレクトさせる方法
functions.phpに記述します

カスタム投稿「news」の場合

function redirect_news_archive_to_latest_single() {
    if ( is_post_type_archive('news') ) { 
        $latest_news = get_posts(array(
            'post_type'      => 'news',
            'posts_per_page' => 1, 
        ));
        if ( !empty($latest_news) ) {
            wp_redirect( get_permalink( $latest_news[0]->ID ), 301 );
            exit;
        }
    }
}
add_action( 'template_redirect', 'redirect_news_archive_to_latest_single' );

通常の投稿(post)の場合

function redirect_post_archive_to_latest_single() {
    if ( is_home() ) { 
        $latest_post = get_posts(array(
            'post_type'      => 'post',
            'posts_per_page' => 1, 
        ));
        if ( !empty($latest_post) ) {
            wp_redirect( get_permalink( $latest_post[0]->ID ), 301 );
            exit;
        }
    }
}
add_action( 'template_redirect', 'redirect_post_archive_to_latest_single' );

2.リンク先URLを最新記事1件目へ変更する

ボタンやメニューのリンク先そのものを、最初から最新記事のURLに置き換えるやり方

カスタム投稿「news」の場合

<?php
$myposts = get_posts( "post_type=news&orderby=date&order=DESC&numberposts=1" );
if ( !empty( $myposts ) ): ?>
  <a href="<?php echo get_permalink( $myposts[0] ); ?>" class="scroll">リンクテキスト</a>
<?php endif; ?>

通常の投稿(post)の場合

<?php
$myposts = get_posts( "post_type=post&orderby=date&order=DESC&numberposts=1" );
if ( !empty( $myposts ) ): ?>
  <a href="<?php echo get_permalink( $myposts[0] ); ?>" class="scroll">リンクテキスト</a>
<?php endif; ?>

コードはすっかりAI頼みになりましたね エラーもすぐ見つかるし…
しかしこの機会に2つのやり方を整理しましたので備忘録もかねてメモします

コメント