函数文档

comment_link()

💡 云策文档标注

概述

comment_link() 函数用于显示评论的链接,基于 get_comment_link() 获取链接并应用过滤器。它接受一个可选的评论对象或 ID 参数,默认使用全局评论对象。

关键要点

  • 函数 comment_link() 直接输出评论的永久链接,适用于模板中显示评论链接。
  • 参数 $comment 可选,可以是整数或 WP_Comment 对象,默认为 null 使用全局评论。
  • 内部使用 get_comment_link() 获取链接,并通过 apply_filters('comment_link', ...) 允许过滤。
  • 输出时使用 esc_url() 确保 URL 安全。
  • 自 WordPress 4.4.0 版本引入 $comment 参数,1.5.0 版本引入函数。

代码示例

// 在模板中使用 comment_link() 显示当前评论的链接
comment_link();

// 传递特定评论 ID 显示链接
comment_link( 123 );

注意事项

确保在评论上下文中调用,否则可能无法正确获取全局评论对象。链接输出已转义,可直接用于 HTML。


📄 原文内容

Displays the link to the comments.

Parameters

$commentint|WP_Commentoptional
Comment object or ID. Defaults to global comment object.

Default:null

Source

function comment_link( $comment = null ) {
	/**
	 * Filters the current comment's permalink.
	 *
	 * @since 3.6.0
	 *
	 * @see get_comment_link()
	 *
	 * @param string $comment_permalink The current comment permalink.
	 */
	echo esc_url( apply_filters( 'comment_link', get_comment_link( $comment ) ) );
}

Hooks

apply_filters( ‘comment_link’, string $comment_permalink )

Filters the current comment’s permalink.

Changelog

Version Description
4.4.0 Introduced the $comment argument.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Create an anchored permalink to a single comment.

    <a href="<?php comment_link(); ?>">Permalink to this comment</a>

    The code shown above will result (depending on your permalink settings) in something like this:

    <a href="<a href="http://example.com/2009/07/15/example-post/comment-page-1/#comment-3">Permalink" rel="nofollow ugc">http://example.com/2009/07/15/example-post/comment-page-1/#comment-3">Permalink</a> to this comment</a>