Skip to content

Instantly share code, notes, and snippets.

@drrobotnik
Created September 23, 2015 19:22
Show Gist options
  • Save drrobotnik/403903c69deed36652ce to your computer and use it in GitHub Desktop.
Save drrobotnik/403903c69deed36652ce to your computer and use it in GitHub Desktop.
redirect requests from matching permastruct pattern to the correct one
add_action( 'wp_loaded', 'tt_redirect_canonical' );
function tt_redirect_canonical() {
$parsed_requested_url = parse_url( $_SERVER['REQUEST_URI'] );
if ( preg_match_all( '/\/[0-9]{4}\/[0-9]{2}\/[0-9]{2}\/(?<post_name>[a-z0-9\-]*)\/?$/', $parsed_requested_url['path'], $matches ) ) {
foreach ( $matches['post_name'] as $match ) {
$args = array(
'name' => $match,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'suppress_filters' => false,
);
$found_post = get_posts( $args );
if ( $found_post ) {
$redirect_url = get_permalink( $found_post[0]->ID );
wp_safe_redirect( $redirect_url, 301 );
die();
}
}
}elseif( preg_match_all( '/^\/([0-9]{4})\/?/', $parsed_requested_url['path'], $matches ) ) {
$redirect_url = '/date' . $parsed_requested_url['path'];
wp_safe_redirect( $redirect_url, 301 );
die();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment