WordPress at a glance

wp_get_attachment_link() WP 1.0

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

  • Since 4.4.0 The $id parameter can now accept either a post ID or WP_Post object.
Is the basis for: the_attachment_link()
Hooks from function:
Return

String. HTML content.

Usage

wp_get_attachment_link( $id, $size, $permalink, $icon, $text, $attr );
$id(int/WP_Post)
Post ID or post object.
Default: 0
$size(string/array)
Image size. Accepts any valid image size, or an array of width and height values in pixels (in that order).
Default: 'thumbnail'
$permalink(true/false)
Whether to add permalink to image.
Default: false
$icon(true/false)
Whether the attachment is an icon.
Default: false
$text(string/false)
Link text to use. Activated by passing a string, false otherwise.
Default: false
$attr(array/string)
Array or string of attributes.
Default: ''

Code of wp_get_attachment_link: wp-includes/post-template.php VER 4.9.8

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

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

	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 a retrieved attachment page link.
	 *
	 * @since 2.7.0
	 *
	 * @param string       $link_html The page link HTML output.
	 * @param int          $id        Post ID.
	 * @param string|array $size      Size of the image. Image size or array of width and height values (in that order).
	 *                                Default 'thumbnail'.
	 * @param bool         $permalink Whether to add permalink to image. Default false.
	 * @param bool         $icon      Whether to include an icon. Default false.
	 * @param string|bool  $text      If string, will be link text. Default false.
	 */
	return apply_filters( 'wp_get_attachment_link', "<a href='" . esc_url( $url ) . "'>$link_text</a>", $id, $size, $permalink, $icon, $text );
}

Related Functions

From category: Attachments (Media files)

More from Template Tags: Posts, Pages, ...

No comments
    Hello, !     Log In . Register