WordPress | re-direct snippet *

Look Ma! No Plugins


  • Check to see if your site has a “trailing slash” a / at the end of the urls
  • get the exact url “slugs” for new / old post url

https://projects.nakedsword.com/complaint-form-info-page/ 
https://projects.nakedsword.com/remove-content-info-page/

SLUGS:
old: /complaint-form-info-page/
new: /remove-content-info-page/



function redirect_page() {

     if (isset($_SERVER['HTTPS']) &&
        ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
        $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $protocol = 'https://';
        }
        else {
        $protocol = 'http://';
    }

    $currenturl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $currenturl_relative = wp_make_link_relative($currenturl);

    switch ($currenturl_relative) {
    
        case '[from slug]':
            $urlto = home_url('[to slug]');
            break;

            /* additional go here
             case '[from slug]':
            $urlto = home_url('[to slug]');
            break;

             case '[from slug]':
            $urlto = home_url('[to slug]');
            break;

            */
        
        default:
            return;
    
    }
    
    if ($currenturl != $urlto)
        exit( wp_redirect( $urlto ) );


}
add_action( 'template_redirect', 'redirect_page' );


Scroll to Top