WordPressページで404 not foundの場合にトップページにリダイレクトを行う

概要説明

パーマリンクを変更したリニューアルの際に構造を変えたりすると検索エンジンからのアクセスで404になるので、404の場合はトップページや任意のページにリダイレクトさせるカスタマイズ。

エラーページの場合にリダイレクト

functions.php
/*----------------------------------------------------
 404 not foundの場合はリダイレクト
----------------------------------------------------*/
if ( !function_exists( 'is404_redirect' ) ){
    function is404_redirect() {
        if( is_404() ){

            $url = '';
            if ( isset($_SERVER['REQUEST_URI']) ) {
                $url = $_SERVER['REQUEST_URI'];
            }

            // URLに特定の文字列が含む場合
            if( strstr($url, '任意の文字列') ){
                //wp_redirect('https://任意のページにリダイレクト', 301); // 301 リダイレクト
                wp_redirect('https://任意のページにリダイレクト');        // 302 リダイレクト

            } else {
                // topページ
                //wp_safe_redirect( home_url( '/' ), 301 );               // 301 リダイレクト
                wp_safe_redirect( home_url( '/' ) );                      // 302 リダイレクト

            }
            exit();
        }
    }
    add_action( 'template_redirect', 'is404_redirect' );
}

URLにて判定してそれ以外はトップページへリダイレクトという処理にしています。url判定が必要ない場合は一律トップページリダイレクトでご利用ください

WordPress Developer Resources

関連機能

  1. Deprecated: Automatic conversion of false to array is deprecated inの対応

  2. WordPress SiteGuard プラグインにて入力を間違えて管理者アカウントがログインロック状態になった場合の解除方法

  3. WordPress 6.7 「Notice: Function _load_textdomain_just_in_time was called incorrectly.」

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

欲しい物があるなら
何もかもかなぐり捨てて
掴みにいくぐらいの方が
人生は楽しいわよ

彼女、お借りします
by 水原千鶴

Profile

PAGE TOP
Amazon プライム対象