get_cancel_comment_reply_link()
云策文档标注
概述
get_cancel_comment_reply_link() 函数用于生成取消评论回复链接的 HTML 内容。它接受可选的链接文本和帖子参数,并返回一个包含 URL 和样式的格式化链接字符串。
关键要点
- 函数返回一个字符串,表示取消评论回复的 HTML 链接。
- 参数 $link_text 可选,默认为 'Click here to cancel reply',可自定义显示文本。
- 参数 $post 可选,用于指定评论线程所属的帖子,默认为当前全局帖子。
- 内部使用 _get_comment_reply_id() 和 remove_query_arg() 等函数处理回复逻辑和 URL。
- 输出通过 'cancel_comment_reply_link' 过滤器进行过滤,允许开发者自定义链接 HTML。
- 从 WordPress 6.2.0 版本开始添加了 $post 参数,增强了灵活性。
代码示例
function get_cancel_comment_reply_link( $link_text = '', $post = null ) {
if ( empty( $link_text ) ) {
$link_text = __( 'Click here to cancel reply.' );
}
$post = get_post( $post );
$reply_to_id = $post ? _get_comment_reply_id( $post->ID ) : 0;
$link_style = 0 !== $reply_to_id ? '' : ' style="display:none;"';
$link_url = esc_url( remove_query_arg( array( 'replytocom', 'unapproved', 'moderation-hash' ) ) ) . '#respond';
$cancel_comment_reply_link = sprintf(
'%3$s',
$link_url,
$link_style,
$link_text
);
return apply_filters( 'cancel_comment_reply_link', $cancel_comment_reply_link, $link_url, $link_text );
}注意事项
- 函数默认在回复 ID 为 0 时隐藏链接(通过 style="display:none;"),确保仅在需要时显示。
- 使用 esc_url() 对 URL 进行清理,防止安全漏洞。
- 相关函数如 cancel_comment_reply_link() 可直接显示此链接,而 get_cancel_comment_reply_link() 仅返回 HTML 字符串。
原文内容
Retrieves HTML content for cancel comment reply link.
Parameters
$link_textstringoptional-
Text to display for cancel reply link. If empty, defaults to ‘Click here to cancel reply’. Default empty.
$postint|WP_Post|nulloptional-
The post the comment thread is being displayed for. Defaults to the current global post.
Default:
null
Source
function get_cancel_comment_reply_link( $link_text = '', $post = null ) {
if ( empty( $link_text ) ) {
$link_text = __( 'Click here to cancel reply.' );
}
$post = get_post( $post );
$reply_to_id = $post ? _get_comment_reply_id( $post->ID ) : 0;
$link_style = 0 !== $reply_to_id ? '' : ' style="display:none;"';
$link_url = esc_url( remove_query_arg( array( 'replytocom', 'unapproved', 'moderation-hash' ) ) ) . '#respond';
$cancel_comment_reply_link = sprintf(
'<a rel="nofollow" id="cancel-comment-reply-link" href="%1$s"%2$s>%3$s</a>',
$link_url,
$link_style,
$link_text
);
/**
* Filters the cancel comment reply link HTML.
*
* @since 2.7.0
*
* @param string $cancel_comment_reply_link The HTML-formatted cancel comment reply link.
* @param string $link_url Cancel comment reply link URL.
* @param string $link_text Cancel comment reply link text.
*/
return apply_filters( 'cancel_comment_reply_link', $cancel_comment_reply_link, $link_url, $link_text );
}
Hooks
- apply_filters( ‘cancel_comment_reply_link’, string $cancel_comment_reply_link, string $link_url, string $link_text )
-
Filters the cancel comment reply link HTML.