Posted by & filed under Code Tips.

Quick little snippet to redirect your visitors to another page after they leave a comment.

function comment_redirect($location, $comment) {
	return site_url('/thanks/'); 
add_filter('comment_post_redirect', 'comment_redirect');

Normally after leaving a comment in WordPress you’re sent back to the page where you left the comment. By using the comment_post_redirect filter you’ll be able to control where they go. As it’s written, this code will redirect back to a /thanks/ page on your site, but you could redirect it anywhere you want.

And a couple of things that are left out of most of the tutorials on this filter that I’ve seen.

First, whatever is returned from your function is where the visitor will be redirected. Of course, it’s a filter so it’s possible that another plugin will override your return value. If you absolutely have to be sure your code is the one that does the redirect you can either make sure your filter is the last in line or just call wp_redirect from the method.

And second, the $comment parameter contains information on the comment that was submitted. You can use this to make decisions on where to redirect. For example, I used this on a site where only comments on a specific custom post type should be redirected differently. One of the elements of the $comments parameter is the post that the comment belongs to. I was able to check the post_type for that post and determine what to do.

Leave a Reply

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