get_attachment_link()
Gets the URL of the media file page on the site (front-end).
If pretty permalinks (human-readable URLs) are enabled, the function will output a link like this:
http://example.com/post_slug/attachment_name
If pretty permalinks are disabled, the URL will be like this (ID — this is the ID of the attachment):
http://example.com/?attachment_id=ID
Use wp_get_attachment_url( $id ) when you need to get the URL to the file itself.
Used By: wp_get_attachment_link(), get_permalink()
Hooks from the function
Returns
String. URL to the attachment page.
Usage
$attachment_page = get_attachment_link( $id );
- $id(int)
- ID of the attachment whose URL you want to get.
Default: id of the current attachment
Examples
#1 Get the URL of the attachment page
// file is not attached to the post echo get_attachment_link( 104 ); //> http://example.com/screenshot_4-3 // file attached to the post echo get_attachment_link( 105 ); //> http://example.com/conditional-fields/vkladka-s-nastrojkoj
#2 Display the link to the attachment
Since the function takes the URL and not the output, we will use the PHP echo command to show the link:
<?php $attachment_id = 1; // attachment ID $attachment_link = get_attachment_link( $attachment_id ); ?> <a href="<?php echo $attachment_page; ?>"><?php echo get_the_title($attachment_id) ?></a>
#3 Display attached images and titles as a list
To display the images attached to a certain page and display them as a list of bullets you can use the following:
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
?>
<li>
<?php the_attachment_link( $attachment->ID, true ) ?>
<p><?= apply_filters( 'the_title', $attachment->post_title ) ?></p>
</li>
<?php
}
}
endwhile; endif; ?>
</ul>
Notes
- Global. WP_Rewrite.
$wp_rewriteWordPress rewrite component.
Changelog
| Since 2.0.0 | Introduced. |