Skip to content

Instantly share code, notes, and snippets.

@stephanieleary
Last active April 26, 2016 20:35
Show Gist options
  • Save stephanieleary/8f75af1cb1b0ba4b037616616127586e to your computer and use it in GitHub Desktop.
Save stephanieleary/8f75af1cb1b0ba4b037616616127586e to your computer and use it in GitHub Desktop.
Redirect 404 errors to posts with old path stored in custom field, if it exists
<?php
add_filter( 'redirect_canonical', 'my_404_no_guessing', 10, 2 );
function my_404_no_guessing( $redirect_url, $request_url ) {
if ( is_404() ) {
// Drupal redirects
$posts = get_posts( array(
'meta_key' => 'drupal_path', // change to your meta_key
'meta_value' => parse_url( $request_url, PHP_URL_PATH ),
'post_type' => 'any',
'posts_per_page' => 1,
'fields' => 'ids',
) );
if ( $posts ) {
$redirect_url = get_permalink( array_pop( $posts ) );
}
else
return false;
}
return $redirect_url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment