I am trying to combine two preg_match patterns separate with ,|,.
/blog\/page\/[0-9]+\/?$/ with /tag\/ skip in /blog/page/ and /tag/
/page\/[0-9]+\/?$/ with /[0-9]+\/?$/ ex. /page/2/ and only /2/
/(page\/[0-9]+\/?)$/ with /([0-9]+\/?)$/
function redirect_pagination() {
if(!preg_match('/blog\/page\/[0-9]+\/?$/,|,/tag\/', $_SERVER['REQUEST_URI'])) {
if(preg_match('/page\/[0-9]+\/?$/,|,/[0-9]+\/?$/', $_SERVER['REQUEST_URI'])) {
$new_url = preg_replace('/(page\/[0-9]+\/?)$/,|,/([0-9]+\/?)$/', '', $_SERVER['REQUEST_URI']);
wp_redirect($new_url, 301);
exit;
}
}
}
add_action( 'init', 'redirect_pagination', 1 );
I am trying to combine two preg_match patterns separate with ,|,.
/blog\/page\/[0-9]+\/?$/ with /tag\/ skip in /blog/page/ and /tag/
/page\/[0-9]+\/?$/ with /[0-9]+\/?$/ ex. /page/2/ and only /2/
/(page\/[0-9]+\/?)$/ with /([0-9]+\/?)$/
function redirect_pagination() {
if(!preg_match('/blog\/page\/[0-9]+\/?$/,|,/tag\/', $_SERVER['REQUEST_URI'])) {
if(preg_match('/page\/[0-9]+\/?$/,|,/[0-9]+\/?$/', $_SERVER['REQUEST_URI'])) {
$new_url = preg_replace('/(page\/[0-9]+\/?)$/,|,/([0-9]+\/?)$/', '', $_SERVER['REQUEST_URI']);
wp_redirect($new_url, 301);
exit;
}
}
}
add_action( 'init', 'redirect_pagination', 1 );
Share
Improve this question
asked May 25, 2019 at 7:08
tw8sw8dw8tw8sw8dw8
733 silver badges10 bronze badges
2
- what do you want to do? – user134414 Commented May 25, 2019 at 16:26
- I want to redirect pages such as /post-name/page/2/, /post-name/2/ to /post-name/ except for /blog/page/ and /tag/. I do this with two functions, but I know it is possible with just one. – tw8sw8dw8 Commented May 25, 2019 at 16:55
1 Answer
Reset to default 1I think this is what you are looking for
if (preg_match('@^/((?!blog|tag)[^/]+)/(?:page/)?\d+@', $_SERVER['REQUEST_URI'], $m)) {
wp_redirect("/$m[1]", 301);
}
The regexp uses lookahead to make sure that the first match isn't blog or tag.
The '[^/]+'
part matches anything that isn't a forward slash (/
).
(?:page/)?
- Makes an optional match against 'page/'
\d+
- Match against any number.
This will not redirect '/blog/2
if you want '/blog/2'
to be redirected but not '/blog/page/2'
then change the regexp above to read 'blog/page'
where it now says 'blog'
.
PS: I know this is 5 months old and you have probably moved on by now but I'll put this here anyway in case someone else needs help with the same issue.