Created
September 23, 2015 19:22
-
-
Save drrobotnik/403903c69deed36652ce to your computer and use it in GitHub Desktop.
redirect requests from matching permastruct pattern to the correct one
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
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