get_edit_comment_link()
云策文档标注
概述
get_edit_comment_link() 函数用于获取评论的编辑链接,支持指定评论 ID 或 WP_Comment 对象,并可控制链接上下文以包含 HTML 实体或纯 URL。该函数会检查当前用户是否有编辑权限,并返回过滤后的链接。
关键要点
- 函数参数:$comment_id(可选,评论 ID 或 WP_Comment 对象,默认 0)和 $context(可选,上下文,'display' 或 'url',默认 'display')。
- 返回值:返回编辑链接 URL 字符串,如果评论不存在或用户无权限则返回 void。
- 权限检查:使用 current_user_can('edit_comment', $comment->comment_ID) 验证用户编辑权限。
- 上下文处理:根据 $context 参数生成不同的链接格式,'display' 时包含 HTML 实体,'url' 时使用纯 URL。
- 过滤器:通过 apply_filters('get_edit_comment_link', $location, $comment_id, $context) 允许自定义链接。
代码示例
function get_edit_comment_link( $comment_id = 0, $context = 'display' ) {
$comment = get_comment( $comment_id );
if ( ! is_object( $comment ) || ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
return;
}
if ( 'display' === $context ) {
$action = 'comment.php?action=editcomment&c=';
} else {
$action = 'comment.php?action=editcomment&c;=';
}
$location = admin_url( $action ) . $comment->comment_ID;
$comment_id = (int) $comment->comment_ID;
return apply_filters( 'get_edit_comment_link', $location, $comment_id, $context );
}注意事项
- 函数在 WordPress 2.3.0 引入,6.7.0 版本添加了 $context 参数。
- 相关函数包括 get_comment()、admin_url()、current_user_can() 和 apply_filters()。
- Hook:apply_filters('get_edit_comment_link', string $location, int $comment_id, string $context) 用于过滤评论编辑链接。
原文内容
Retrieves the edit comment link.
Parameters
$comment_idint|WP_Commentoptional-
Comment ID or WP_Comment object.
$contextstringoptional-
Context in which the URL should be used. Either
'display', to include HTML entities, or'url'. Default'display'.
Source
function get_edit_comment_link( $comment_id = 0, $context = 'display' ) {
$comment = get_comment( $comment_id );
if ( ! is_object( $comment ) || ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
return;
}
if ( 'display' === $context ) {
$action = 'comment.php?action=editcomment&c=';
} else {
$action = 'comment.php?action=editcomment&c;=';
}
$location = admin_url( $action ) . $comment->comment_ID;
// Ensure the $comment_id variable passed to the filter is always an ID.
$comment_id = (int) $comment->comment_ID;
/**
* Filters the comment edit link.
*
* @since 2.3.0
* @since 6.7.0 The $comment_id and $context parameters are now being passed to the filter.
*
* @param string $location The edit link.
* @param int $comment_id Unique ID of the comment to generate an edit link.
* @param string $context Context to include HTML entities in link. Default 'display'.
*/
return apply_filters( 'get_edit_comment_link', $location, $comment_id, $context );
}
Hooks
- apply_filters( ‘get_edit_comment_link’, string $location, int $comment_id, string $context )
-
Filters the comment edit link.