钩子文档

comment_post_redirect

💡 云策文档标注

概述

comment_post_redirect 是一个 WordPress 过滤器,用于在用户提交评论后重定向到指定 URI。它允许开发者自定义重定向位置,例如在自定义页面中处理评论时保持页面跳转。

关键要点

  • 过滤器名称:comment_post_redirect
  • 参数:$location(重定向 URI 字符串)和 $comment(WP_Comment 对象)
  • 用途:修改评论提交后的重定向目标,常用于自定义页面或特定帖子类型
  • 引入版本:WordPress 2.0.5

代码示例

add_filter( 'comment_post_redirect', 'redirect_comments', 10, 2 );
function redirect_comments( $location, $commentdata ) {
  if ( ! isset( $commentdata ) || empty( $commentdata->comment_post_ID ) ) {
    return $location;
  }
  $post_id = $commentdata->comment_post_ID;
  if ( 'my-custom-post' == get_post_type( $post_id ) ) {
    return wp_get_referer() . "#comment-" . $commentdata->comment_ID;
  }
  return $location;
}

注意事项

  • 使用此过滤器时,需同时处理 comment_reply_link 过滤器以修改评论回复链接
  • 确保检查 $commentdata 参数的有效性,避免空值错误

📄 原文内容

Filters the location URI to send the commenter after posting.

Parameters

$locationstring
The 'redirect_to' URI sent via $_POST.
$commentWP_Comment
Comment object.

Source

$location = apply_filters( 'comment_post_redirect', $location, $comment );

Changelog

Version Description
2.0.5 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Sometimes you want to build a page with various custom posts displayed on the same page and use one of these post’s comments to handle the page comments. However, when you submit a comment associate with a given post, the submit button redirects you to that post’s permalink, and not to your original page. To overcome this, you need to filter the redirect location such as,

    add_filter( 'comment_post_redirect', 'redirect_comments', 10,2 );
    function redirect_comments( $location, $commentdata ) {
      if(!isset($commentdata) || empty($commentdata->comment_post_ID) ){
        return $location;
      }
      $post_id = $commentdata->comment_post_ID;
      if('my-custom-post' == get_post_type($post_id)){
        return wp_get_referer()."#comment-".$commentdata->comment_ID;
      }
      return $location;
    }

    Don’t forget to also change the ‘Reply’ button links on comments using the filter comment_reply_link