WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] A simple redirect using comment_post_redirect in functions.php (7 posts)

  1. jimmiejo
    Member
    Posted 4 years ago #

    I've broken my posts and comments into two tabs, the second of which is called #comments. An issue arises when a comment is posted, as the reader is directed to a #comment-259 url. That of course breaks my tab feature.

    To correct this, I'm using a simple function to filter the url users are redirected to after they post a comment:

    add_filter('comment_post_redirect', 'redirect_after_comment');
    function redirect_after_comment($location)
    {
    return '/need-it-to-be-the-permalink#comments';
    }

    I simply need to know how to fetch the permalink of the post the user commented on, and use that in the "return" url in the above function (where I typed /need-it-to-be-the-permalink#comments)

    Thanks, WP-ers.

  2. jimmiejo
    Member
    Posted 4 years ago #

    By modifying /wp-includes/comment-template.php from:

    return apply_filters( 'get_comment_link', $link . '#comment-' . $comment->comment_ID, $comment, $args );

    to:

    return apply_filters( 'get_comment_link', $link . '#comments', $comment, $args );

    ...I was able to do achieve what I needed, but this would be much better in my functions.php. Can anyone format an add_filter function with my modified code above, please?

  3. Aesqe
    Member
    Posted 4 years ago #

    haven't tried it, but this should work :)

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

  4. jimmiejo
    Member
    Posted 4 years ago #

    Worked like a charm :) A mighty thanks to you, aesqe!

  5. Aesqe
    Member
    Posted 4 years ago #

    sorry, that should've been:

    add_filter('get_comment_link', 'redirect_after_comment');
    function redirect_after_comment($location)
    {
        return preg_replace("/#comment-([\d]+)/", "#comments", $location);
    }
  6. Aesqe
    Member
    Posted 4 years ago #

    oh, the above worked? ok, haha, glad i could help ;)

  7. jimmiejo
    Member
    Posted 4 years ago #

    It did! :)

Topic Closed

This topic has been closed to new replies.

About this Topic