Add Snippet To Project
If you’re looking for a way to improve user experience on your WordPress site, consider redirecting commenters to a thank you post or page after they leave a comment. This simple step can show your appreciation for their engagement and keep them coming back for more. In this article, we’ll discuss how to set up a redirect for commenters and optimize your thank you page for maximum impact.
function wpturbo_comment_redirect( $location, $comment ) {
$comment_post_ID = $comment->comment_post_ID;
$thankyou_page_id = get_post_meta( $comment_post_ID, 'wpturbo_thankyou_page', true );
if ( $thankyou_page_id ) {
return get_permalink( $thankyou_page_id );
} else {
return $location;
}
}
add_filter( 'comment_post_redirect', 'wpturbo_comment_redirect', 10, 2 );
The purpose of this code snippet is to redirect a commenter to a custom page or post after leaving a comment on a WordPress site. This can be useful for providing a thank you message or other relevant content to the commenter.
First, we define a function called wpturbo_comment_redirect()
that will handle the redirection. This function accepts two parameters: $location
and $comment
. $location
is the current URL the user is being directed to after leaving a comment, and $comment
is the comment object, which includes the information about the comment the user just left.
Next, we use $comment
to get the ID of the post the comment was left on with $comment_post_ID = $comment->comment_post_ID;
. We then use get_post_meta()
to retrieve the ID of the custom thank you page associated with the post the comment was left on. This ID is stored as post meta with the key wpturbo_thankyou_page
.
If a custom thank you page ID is found, we use get_permalink()
to get the URL for the custom page and return it. This is done with return get_permalink( $thankyou_page_id );
. If no custom thank you page is set, we simply return the original $location
value to allow the commenter to be redirected to the default page after commenting.
Finally, we hook the wpturbo_comment_redirect()
function into the comment_post_redirect
filter with add_filter( 'comment_post_redirect', 'wpturbo_comment_redirect', 10, 2 );
. This ensures that the redirection happens after a comment is left on the site.