Last active
February 8, 2017 16:25
-
-
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!
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
<?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); | |
} | |
} | |
?> |
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
You can see a working example here: http://chefgrill.de/testberichte/weber-q100-testbericht/.
Try adding some numbers, e.g. http://chefgrill.de/testberichte/weber-q100-testbericht/35245235124/ or http://franzis-backstube.de/zitronen-cupcakes-zum-osterfest/42563234563/ and see how it works.