i’ve a problem concerning a PHP function for a WordPress site. As of this article https://perishablepress.com/wordpress-infinite-duplicate-content/ WordPress has a problem for infinite pagination. So i need to fix this by catching numbered URLs and redirecting them to its parent URL.
I found this code online but i’ve modified it just a little bit for my needs. It works as expected, but it doesn’t catch URLs that contains zero and also not redirect directly to a URL with slash (if there isn’t one in the fetched URL).
From my tests, it appears that PHP is not catching the URLs that contain 0
with the parameter is_numeric
(probably because 0 is considered an int
, but i’m not sure). I’m not familiar with PHP, so i’m sharing this with you.
For the rest, it works perfectly, catching numbered URLs and redirecting to its parent URL. Of course, i’ve already closed the code into a function and loaded in an hook. But i’ll share only the code itself just for better clarification:
global $posts, $numpages; $request_uri = $_SERVER['REQUEST_URI']; $result = preg_match('%/(d)+(/)?$%', $request_uri, $matches); $ordinal = $result ? intval($matches[1]) : FALSE; if(is_numeric($ordinal)) { // a numbered page was requested: validate it // look-ahead: initialises the global $numpages setup_postdata($posts[0]); // yes, hack $redirect_to = ($ordinal) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE); if(is_string($redirect_to)) { // we got us a phantom $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri); // if page = 0 or 1, redirect permanently if($ordinal) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); } header("Location: $redirect_url"); exit(); } }
I’m expecting that numbered URLs, also that contains 000000
or 01234
, are also redirected to its parent source. Thanks for the help.
Advertisement
Answer
is_numeric() calls for values like ‘0000’ and ‘0123’ will return true in php and those will be parsed into 0 and 123 as you would expect via intval().
I notice that you have changed the original code in the blog post from
// if page = 0 or 1, redirect permanently ($ordinal < 2) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); } else { header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found'); }
to
// if page = 0 or 1, redirect permanently if($ordinal) { header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); }
The comment no longer matches the functionality, maybe because you always want that 301 functionality for your uses?
I believe your code would handle a 0000 ordinal differently because it will evaluate false in that if check.
If I’m right in understanding what you want, you could try removing that if check altogether and see if it resolves your issue. If not can you provide some full URLs that exhibit the problem?