Skip to content

Instantly share code, notes, and snippets.

@jemoreto
Created September 1, 2017 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jemoreto/36bf6ea8daf6d6e571295c9f0f99e040 to your computer and use it in GitHub Desktop.
Save jemoreto/36bf6ea8daf6d6e571295c9f0f99e040 to your computer and use it in GitHub Desktop.
WordPress redirect 404 with valid slug
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' );
@jemoreto
Copy link
Author

jemoreto commented Sep 1, 2017

Useful if you changed your WordPress installation and/or your permalink structure.

@AdilanBill
Copy link

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