In wordpress, how to redirect after a comment back to the referring page?
I would advise against returning $_SERVER["HTTP_REFERER"]
as it's not reliable.
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Source https://php.net/manual/en/reserved.variables.server.php
Here's an alternative
add_filter( 'comment_post_redirect', function ( $location ) {
return get_permalink($_POST['comment_post_ID']);
} );
Use the WordPress Plugin API. It's the proper way to extend or customize functionality in WordPress. Once you've read a little about the API, check out the Action Reference (I would post the link but StackOverflow wont let me).
You will need at least two action hooks to complete your task:
- comment_post - run directly after a comment is added to your database
- comment_form - run whenever the comment form is printed from a theme template
Basically, we want to capture the HTTP_REFERER variable in the persistent $_SESSION whenever the user first sees the comment form. Then we redirect them once they post the comment.
Create comment-redirect.php
in the WordPress wp-content/plugins
folder.
Here's a rough idea of what you would put in this file (I leave it up to you to refine/test it):
<?php
/*
Plugin Name: Post Comment Redirect
Plugin URI: http://example.com
Description: Redirects you to the previous page after posing a comment
Version: 0.1a
Author: Anonymous
Author URI: http://example.com
License: GPL2
*/
// Run whenever a comment is posted to the database.
// If a previous page url is set, then it is unset and
// the user is redirected.
function post_comment_redirect_action_comment_post() {
if (isset($_SESSION['PCR_PREVIOUS_PAGE_URL'])) {
$ref = $_SESSION['PCR_PREVIOUS_PAGE_URL'];
unset($_SESSION['PCR_PREVIOUS_PAGE_URL']);
header('Location: '.$ref);
}
}
// Run whenever comment form is shown.
// If a previous page url is not set, then it is set.
function post_comment_redirect_action_comment_form() {
if (!isset($_SESSION['PCR_PREVIOUS_PAGE_URL'])) {
if ($ref = $_SERVER['HTTP_REFERER']) {
$_SESSION['PCR_PREVIOUS_PAGE_URL'] = $ref;
}
}
}
add_action('comment_post', 'post_comment_redirect_action_comment_post');
add_action('comment_form', 'post_comment_redirect_action_comment_form');
Once you have your plugin saved, enable it in the wp-admin Plugins section (usually found near h**p://your-website-address.com/wp-admin).
Put this in your functions.php:
add_filter('comment_post_redirect', 'redirect_after_comment');
function redirect_after_comment($location)
{
return $_SERVER["HTTP_REFERER"];
}