我在Wordpress中的不同类型的页面上启用了评论(存档,标记,搜索,主页),并且在用户发布评论后我希望将它们重定向回其引用页面,而不是单个帖子页。有什么想法吗?
答案 0 :(得分:16)
将其放入 functions.php :
add_filter('comment_post_redirect', 'redirect_after_comment');
function redirect_after_comment($location)
{
return $_SERVER["HTTP_REFERER"];
}
答案 1 :(得分:3)
使用WordPress Plugin API。这是在WordPress中扩展或自定义功能的正确方法。一旦你读了一些关于API的内容,请查看Action Reference(我会发布链接,但StackOverflow不会让我)。
您需要至少两个操作挂钩才能完成任务:
基本上,只要用户第一次看到评论表单,我们就想捕获持久化$ _SESSION中的HTTP_REFERER变量。然后我们在发表评论后重定向他们。
在WordPress comment-redirect.php
文件夹中创建wp-content/plugins
以下是您将在此文件中添加的内容的粗略概念(我将其留给您进行优化/测试):
<?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');
保存插件后,请在wp-admin插件部分(通常位于h ** p://your-website-address.com/wp-admin附近)启用它。
答案 2 :(得分:0)
我建议不要返回$_SERVER["HTTP_REFERER"]
,因为它不可靠。
将用户代理引至网页的页面地址(如果有) 当前页面。这是由用户代理设置的。并非所有用户代理都会 进行设置,并且某些功能可以将HTTP_REFERER修改为 特征。简而言之,它不能真正被信任。
来源https://php.net/manual/en/reserved.variables.server.php
这是另一种选择
add_filter( 'comment_post_redirect', function ( $location ) {
return get_permalink($_POST['comment_post_ID']);
} );
答案 3 :(得分:-2)
$ref = $_SERVER["HTTP_REFERER"];
header("Location: $ref");