Skip to content

Instantly share code, notes, and snippets.

@gopeter
Last active February 8, 2017 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gopeter/5576584 to your computer and use it in GitHub Desktop.
Save gopeter/5576584 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);
}
}
?>
@gopeter
Copy link
Author

gopeter commented Jun 17, 2013

@codex73
Copy link

codex73 commented Jan 18, 2017

Nice! Do you usually include this snippet on your header file or implement elsewhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment