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. WordPressでのメモリ上限エラー対応 PHP Fatal error: Allowed memory size of xxx bytes exhausted

  2. Notice: Undefined index: post_typeの対応

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

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

当たり前と思われる所にこそ
答えは隠されているものだ

STEINS;GATE
by 岡部 倫太郎

Profile

PAGE TOP
Amazon プライム対象