Created
September 1, 2017 21:54
-
-
Save jemoreto/36bf6ea8daf6d6e571295c9f0f99e040 to your computer and use it in GitHub Desktop.
WordPress redirect 404 with valid slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function q11_redirect_uri_site_antigo() { | |
if ( is_404() ) { | |
$url = 'INSERT_YOUR_DOMAIN_HERE' . $_SERVER['REQUEST_URI']; | |
$end = end(explode('/', rtrim($url, '/'))); | |
if ($end) { | |
if ( $post = get_page_by_path( $end, OBJECT, array('post', 'page'))) { | |
$id = $post->ID; | |
} else { | |
$id = 0; | |
} | |
if ($id !== 0) { | |
$url_redir = get_permalink($id) . '?utm_source=page_404&utm_campaign=auto_redirect'; | |
wp_safe_redirect( $url_redir, '301' ); | |
exit; | |
} | |
} | |
} | |
} | |
add_action( 'template_redirect', 'q11_redirect_uri_site_antigo' ); |
Hi! I think this code is what I've been looking for.
I am new to Wordpress and I really appreciate if you can tell me how to use this code. Should I copy the file to a specific directory or something?
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful if you changed your WordPress installation and/or your permalink structure.