Redirect to page 2 after comment

I would like to have commenters going to the page 2 of a paginated post. My posts are separated by the !--more-- tag so i have the www.site.com/post-title and www.site.com/post-title/2/. I want users to visit the second part of the post after commenting.

I found other questions explaining how to move the user to the paginated comment, that is www.site.com/post-title/comment-page-x/#comment-x but not to other pages of a paginated post.

Edit: My site has the common setting for permalink that is wpinstallation/%postname%/. When paginated, it becomes /%postname%/2/ for page 2.

Thanks.

Topic split read-more redirect pagination comments Wordpress

Category Web


After reading a bit on regex and preg, starting from a previous example of a similar problem and testing it I was able to answer my own question.

I added this function to functions.php:

<?php
/** Plugin Name: WPSE (#167237) Redirect after comment */

add_filter('comment_post_redirect', 'redirect_after_comment');
function redirect_after_comment($location)
{
    return preg_replace("/comment-page-([\d]+)\/#comment-([\d]+)/", "2", $location);
}

It's replacing the part of the url stating the comment page and comment anchor with "2". It may not be the cleanest solution but it's how I managed to do as a beginner.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.