get_comments_link()
云策文档标注
概述
get_comments_link() 函数用于获取当前文章评论的链接,返回一个包含 '#comments' 或 '#respond' 哈希的完整永久链接。它接受一个可选的 $post 参数,并可通过 'get_comments_link' 过滤器进行修改。
关键要点
- 函数返回当前文章评论的链接字符串,基于文章永久链接和评论数量自动附加 '#comments'(有评论时)或 '#respond'(无评论时)。
- 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post 变量。
- 内部使用 get_comments_number() 和 get_permalink() 函数来构建链接。
- 提供 'get_comments_link' 过滤器钩子,允许开发者自定义返回的评论链接。
- 相关函数包括 get_comments_number()、get_permalink() 和 apply_filters(),常用于评论相关功能开发。
代码示例
function get_comments_link( $post = 0 ) {
$hash = get_comments_number( $post ) ? '#comments' : '#respond';
$comments_link = get_permalink( $post ) . $hash;
/**
* Filters the returned post comments permalink.
*
* @since 3.6.0
*
* @param string $comments_link Post comments permalink with '#comments' appended.
* @param int|WP_Post $post Post ID or WP_Post object.
*/
return apply_filters( 'get_comments_link', $comments_link, $post );
}注意事项
- 确保在调用函数前已设置好全局 $post 变量,或显式传递 $post 参数以避免错误。
- 使用 'get_comments_link' 过滤器时,注意回调函数的参数顺序和类型,以正确修改链接。
- 此函数自 WordPress 1.5.0 版本引入,兼容性良好,适用于大多数主题和插件开发场景。
原文内容
Retrieves the link to the current post comments.
Parameters
Source
function get_comments_link( $post = 0 ) {
$hash = get_comments_number( $post ) ? '#comments' : '#respond';
$comments_link = get_permalink( $post ) . $hash;
/**
* Filters the returned post comments permalink.
*
* @since 3.6.0
*
* @param string $comments_link Post comments permalink with '#comments' appended.
* @param int|WP_Post $post Post ID or WP_Post object.
*/
return apply_filters( 'get_comments_link', $comments_link, $post );
}
Hooks
- apply_filters( ‘get_comments_link’, string $comments_link, int|WP_Post $post )
-
Filters the returned post comments permalink.
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |