Redirect to custom URL after adding Comment – WordPress

A function that helps you to redirect to any custom page after posting WordPress comment. WordPress provides many filters to do this custom redirection. Few of tricks are explaining in this article as below:

In WordPress, You can do this thing using 2 ways:

  • using hidden field in comment form
  • using action hook

Before processing next, You assure that you have already created custom page (Here we call it THANK YOU page). You can easily add this page by following way :
Go to your WordPress Dashboard -> Pages -> Add New
and put some interesting content there.

After adding page, You have to get this page URL (I assume this page URL like below: )

Method-1: Using hidden field in comment form

This is very easy and quick way. Open your comments.php file in the theme folder (/wp-content/themes/your-theme), you’ll find something looks like:

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" id="commentform" method="post">

You only need to add line as below:

<input name="redirect_to" type="hidden" value="http://your-domain.com/thank-you" />

As you see the URL of Thank you page is used as the value of the hidden field.

Method-2: Using action hook

In this method, we’ll use the comment_post_redirect action hook. Open your functions.php file in theme folder and insert these lines:

// Redirect to thank you post after comment
add_action('comment_post_redirect', 'redirect_to_thankyou_page_callback');


function redirect_to_thankyou_page_callback() {
// Here you have to define redirecting url
return 'http://your-domain.com/thank-you';
}

 

It’s enough for this article. Stay connect for some new tricks.

Published
Categorized as WordPress

By Ashutosh Pratap

I am software developer by profession and doing work and research in field of Computer programmings like PHP, WordPress, Magento, jQuery, Google APIs and many more web languages. Apart from this I write blogs on programming languages like PHP, Javascript, WordPress etc. I am also individual and independent Freelancer so you can hire me for your web work.

Leave a comment

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