Skip to content

Instantly share code, notes, and snippets.

@codex73
Forked from gopeter/redirect.php
Created February 8, 2017 16:25
Show Gist options
  • Select an option

  • Save codex73/57bb56e79390d758d31f10ef5c5bdce8 to your computer and use it in GitHub Desktop.

Select an option

Save codex73/57bb56e79390d758d31f10ef5c5bdce8 to your computer and use it in GitHub Desktop.
A simple snippet to remove trailing numbers at the end of wordpress urls. For example: redirect http://example.com/foobar/2024/ to http://example.com/foobar/. Don't use it if your permalink structure ends with "%post_id%"! This will return an infinite redirect-loop!
<?php
// get the url
$url = 'http://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
// check if there are any slashes inside the url string
if (strpos($url, '/')) {
// split the string in pieces
// use "/" as separator
$url_pieces = split('/', $url);
// we need the index of the last piece to check if it contains numbers ...
// ... but we have to substract 1 cause an array starts with 0 ...
// ... and we have to substract another 1: the last piece is empty because urls have a trailing "/" and we are using "/" as seperator
$last_index = count($url_pieces) - 2;
// get the last piece
$last_url_piece = $url_pieces[$last_index];
// check if the last piece contains only numbers
if (preg_match('/^[0-9]*$/', $last_url_piece)) {
// get the correct canonical url
$new_url = get_permalink($post->ID);
// redirect via 301 redirection
wp_redirect($new_url, 301);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment