wp_get_attachment_link
云策文档标注
概述
wp_get_attachment_link 是一个 WordPress 过滤器,用于修改获取的附件页面链接的 HTML 输出。它允许开发者在链接生成时自定义其内容、属性和行为。
关键要点
- 过滤器名称:wp_get_attachment_link,用于过滤附件页面链接的 HTML 输出。
- 参数:包括 $link_html(链接 HTML)、$post(文章 ID 或对象)、$size(图像尺寸)、$permalink(是否添加永久链接)、$icon(是否包含图标)、$text(链接文本)和 $attr(属性数组或字符串)。
- 用途:常用于自定义附件链接的显示方式,例如修改链接文本、添加额外属性或调整图像尺寸。
- 版本历史:从 WordPress 2.7.0 引入,5.1.0 版本添加了 $attr 参数。
代码示例
add_filter('wp_get_attachment_link', 'custom_attachment_link', 10, 7);
function custom_attachment_link($link_html, $post, $size, $permalink, $icon, $text, $attr) {
// 自定义逻辑,例如添加 CSS 类
$attr['class'] = 'custom-attachment-link';
// 返回修改后的链接 HTML
return $link_html;
}注意事项
- 确保在添加过滤器时正确处理所有参数,以避免意外行为。
- 使用此过滤器时,注意 $post 参数可以是 0 表示当前全局文章,需进行适当检查。
- 在修改 $attr 参数时,确保其格式为数组或字符串,以兼容不同调用场景。
原文内容
Filters a retrieved attachment page link.
Parameters
$link_htmlstring-
The page link HTML output.
$postint|WP_Post-
Post ID or object. Can be 0 for the current global post.
$sizestring|int[]-
Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).
$permalinkbool-
Whether to add permalink to image. Default false.
$iconbool-
Whether to include an icon.
$textstring|false-
If string, will be link text.
$attrarray|string-
Array or string of attributes.
Source
return apply_filters( 'wp_get_attachment_link', $link_html, $post, $size, $permalink, $icon, $text, $attr );