I have this example link: /uncategorized/hello-world/
If I put 1 page break on the post content, redirects are as follows:

/uncategorized/hello-world/1 => /uncategorized/hello-world/
redirect and is my ideal behavior.

/uncategorized/hello-world/2 => /uncategorized/hello-world/2
no redirect, it’s expected.

/uncategorized/hello-world/3 => /uncategorized/hello-world/
redirect and is my ideal behavior.

BUT if I remove the page break on the post content, only /uncategorized/hello-world/1 works.
If page is 1, it removes the 1 in the url, but other than that it accepts the number.

/uncategorized/hello-world/1 => /uncategorized/hello-world/
/uncategorized/hello-world/2 => /uncategorized/hello-world/2
/uncategorized/hello-world/99 => /uncategorized/hello-world/99

Is there any way to make it so any number should redirect as if there was no number at all.

/uncategorized/hello-world/1 => /uncategorized/hello-world/
/uncategorized/hello-world/2 => /uncategorized/hello-world/
/uncategorized/hello-world/99 => /uncategorized/hello-world/
But only when there’s no page break added on the post.

1 Answer
1

That’s actually the default behavior when the post does not have any page breaks (i.e. the <!--nextpage--> tag).

More specifically, in redirect_canonical(), WordPress only performs a redirect if the post has the page break tag — and that the page number is invalid (e.g. requesting for page #3 when there are only 2 pages). Otherwise (i.e. no page breaks), those paginated URLs/requests are seen as valid and WordPress doesn’t do any redirects except for the first page (e.g. /hello-world/1) because the content is considered a duplicate of /hello-world.

So for those “valid” requests, if you want to redirect them to the first page, you can use the pre_handle_404 hook like so:

add_filter( 'pre_handle_404', function ( $bool ) {
    if ( is_singular( [ 'post', 'page', 'etc' ] ) && get_query_var( 'page' ) &&
        false === strpos( get_queried_object()->post_content, '<!--nextpage-->' )
    ) {
        wp_redirect( get_permalink( get_queried_object() ) );
        exit;
    }

    return $bool;
} );

You can also use the wp hook, but the pre_handle_404 seems better since it’s called first:

add_action( 'wp', function ( $wp ) {
    if ( is_singular( [ 'post', 'page', 'etc' ] ) && get_query_var( 'page' ) &&
        false === strpos( get_queried_object()->post_content, '<!--nextpage-->' )
    ) {
        wp_redirect( get_permalink( get_queried_object() ) );
        exit;
    }
} );

And I’m using is_singular() to target singular requests like single Post (post type post) pages.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *