函数文档

wp_get_attachment_link()

💡 云策文档标注

概述

wp_get_attachment_link() 函数用于获取附件页面的链接,可返回包含图像或图标的 HTML 内容。它支持多种参数配置,如指定图像尺寸、是否链接到附件页面、自定义链接文本等。

关键要点

  • 函数返回 HTML 字符串,用于显示附件链接,默认使用缩略图作为链接内容。
  • 参数包括 $post(附件 ID 或对象)、$size(图像尺寸)、$permalink(是否链接到附件页面)、$icon(是否为图标)、$text(自定义链接文本)和 $attr(HTML 属性)。
  • 内部逻辑:首先验证附件存在,然后根据参数生成链接 URL 和文本,最终应用过滤器 wp_get_attachment_link 和 wp_get_attachment_link_attributes 进行输出。
  • 相关函数包括 wp_get_attachment_image()、wp_get_attachment_url() 等,用于辅助处理附件数据。

代码示例

// 示例:链接附件到附件页面
wp_get_attachment_link( $attachment_id, 'medium', true );

// 示例:显示中等尺寸附件
wp_get_attachment_link( $attachment_id, 'medium' );

// 示例:使用自定义链接文本
wp_get_attachment_link( $attachment_id, 'thumbnail', false, false, 'My link text' );

// 示例:更改图标目录(通过过滤器)
add_filter( 'icon_dir', 'wpdocs_theme_icon_directory' );
add_filter( 'icon_dir_uri', 'wpdocs_theme_icon_uri' );
function wpdocs_theme_icon_directory( $icon_dir ) {
    return get_stylesheet_directory() . '/images';
}
function wpdocs_theme_icon_uri( $icon_dir ) {
    return get_stylesheet_directory_uri() . '/images';
}

注意事项

  • $permalink 参数控制链接目标:false 时链接到媒体文件,true 时链接到附件页面,对应后台“链接到”选项。
  • 如果 $text 参数为字符串,则使用该文本作为链接内容;否则根据 $size 生成图像或回退到附件标题。
  • 函数从 WordPress 2.5.0 版本引入,4.4.0 版本起 $post 参数支持 WP_Post 对象。

📄 原文内容

Retrieves an attachment page link using an image or icon, if possible.

Parameters

$postint|WP_Postoptional
Post ID or post object.
$sizestring|int[]optional
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default 'thumbnail'.
$permalinkbooloptional
Whether to add permalink to image.

Default:false

$iconbooloptional
Whether the attachment is an icon.

Default:false

$textstring|falseoptional
Link text to use. Activated by passing a string, false otherwise.

Default:false

$attrarray|stringoptional
Array or string of attributes. Default empty.

Return

string HTML content.

Source

function wp_get_attachment_link( $post = 0, $size = 'thumbnail', $permalink = false, $icon = false, $text = false, $attr = '' ) {
	$_post = get_post( $post );

	if ( empty( $_post ) || ( 'attachment' !== $_post->post_type ) || ! wp_get_attachment_url( $_post->ID ) ) {
		return __( 'Missing Attachment' );
	}

	$url = wp_get_attachment_url( $_post->ID );

	if ( $permalink ) {
		$url = get_attachment_link( $_post->ID );
	}

	if ( $text ) {
		$link_text = $text;
	} elseif ( $size && 'none' !== $size ) {
		$link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $attr );
	} else {
		$link_text = '';
	}

	if ( '' === trim( $link_text ) ) {
		$link_text = $_post->post_title;
	}

	if ( '' === trim( $link_text ) ) {
		$link_text = esc_html( pathinfo( get_attached_file( $_post->ID ), PATHINFO_FILENAME ) );
	}

	/**
	 * Filters the list of attachment link attributes.
	 *
	 * @since 6.2.0
	 *
	 * @param array $attributes An array of attributes for the link markup,
	 *                          keyed on the attribute name.
	 * @param int   $id         Post ID.
	 */
	$attributes = apply_filters( 'wp_get_attachment_link_attributes', array( 'href' => $url ), $_post->ID );

	$link_attributes = '';
	foreach ( $attributes as $name => $value ) {
		$value            = 'href' === $name ? esc_url( $value ) : esc_attr( $value );
		$link_attributes .= ' ' . esc_attr( $name ) . "='" . $value . "'";
	}

	$link_html = "<a$link_attributes>$link_text</a>";

	/**
	 * Filters a retrieved attachment page link.
	 *
	 * @since 2.7.0
	 * @since 5.1.0 Added the `$attr` parameter.
	 *
	 * @param string       $link_html The page link HTML output.
	 * @param int|WP_Post  $post      Post ID or object. Can be 0 for the current global post.
	 * @param string|int[] $size      Requested image size. Can be any registered image size name, or
	 *                                an array of width and height values in pixels (in that order).
	 * @param bool         $permalink Whether to add permalink to image. Default false.
	 * @param bool         $icon      Whether to include an icon.
	 * @param string|false $text      If string, will be link text.
	 * @param array|string $attr      Array or string of attributes.
	 */
	return apply_filters( 'wp_get_attachment_link', $link_html, $post, $size, $permalink, $icon, $text, $attr );
}

Hooks

apply_filters( ‘wp_get_attachment_link’, string $link_html, int|WP_Post $post, string|int[] $size, bool $permalink, bool $icon, string|false $text, array|string $attr )

Filters a retrieved attachment page link.

apply_filters( ‘wp_get_attachment_link_attributes’, array $attributes, int $id )

Filters the list of attachment link attributes.

Changelog

Version Description
4.4.0 The $post parameter can now accept either a post ID or WP_Post object.
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 11 content

    Change Icon Directory
    WordPress can use media icons to represent attachment files on your blog and in the admin interface, if those icons are available. For images it returns the thumbnail. For other media types it looks for image files named by media type (e.g. audio.jpg) in the directory: wp-includes/images/crystal/.

    This example shows how you can change this directory to a folder called “images” in your theme: wp-content/themes/yourtheme/images. Create the folder and put the “media type images” in there. To tell WordPress the directory has changed put this in the current theme’s functions.php file:

    add_filter( 'icon_dir', 'wpdocs_theme_icon_directory' );
    add_filter( 'icon_dir_uri', 'wpdocs_theme_icon_uri' );
    
    /**
     * Get the path to the icon directory
     */
    function wpdocs_theme_icon_directory( $icon_dir ) {
    	return get_stylesheet_directory() . '/images';
    }
    
    /**
     * Get the URI of the icon directory
     */
    function wpdocs_theme_icon_uri( $icon_dir ) {
    	return get_stylesheet_directory_uri() . '/images'; 
    }

  2. Skip to note 12 content

    I was trying to figure out how to link to the “attachment page” rather than the “media file”, and it took me way to long to make sense of the $permalink parameter. I only figured it out by one of the user-contributed examples. Perhaps you could make it more clear by making its name correspond to the terms used in admin when adding an image to a page / post: “link to” – with options of “media file”, “attachment page”, or “custom URL” (entered by the user).