I have a strange problem with wp_redirect that I can't seem to solve myself.

I'm trying to redirect previously existing pages back to the root of the page so:

http://example.com/slug/page/5/?sort=no-image would redirect back to http://example.com/slug/?sort=no-image in case the page number doesn't exist anymore.

I hooked into template_redirect with the bellow function but for some reason I end up in a redirect loop. What am I doing wrong?

Edit: Forgot to mention that the URL ending in the redirect loop also has a query string appended.

function filter_redirect() {
global $wp_query, $wp;
$requested_url = add_query_arg( $_SERVER['QUERY_STRING'], '', trailingslashit(home_url( $wp->request )) );
$redirect_url = preg_replace('#/page/[0-9]+?(/+)?$#', '/', $requested_url);
$current_page = (get_query_var('paged'));
if ($current_page > $wp_query->max_num_pages) {
add_action('template_redirect', 'filter_redirect' );
  • Had you tried dumping all of it and seeing if conditions and URLs are what you expect them to be?
    – Rarst
    Sep 8, 2014 at 21:35
  • Yes, the url prints the same as in the browser and the condition is met as long as the current page number is greater than the max_num_pages. This is a follow up on question 160381 .
    – ovidiubica
    Sep 8, 2014 at 21:40

1 Answer 1


Changing the regex to


worked for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.