检索附件的永久链接。
原型
get_attachment_link( int|object $post = null, bool $leavename = false )
描述
这可以在WordPress循环或其外部使用。
参数
$post
(int|object)
(Optional)
邮政ID或对象。默认使用全局$ post。
$leavename
(bool)
(Optional)
是否保留页面名称。
返回值
(string)
附件永久链接。
源文件
路径:wp-includes/link-template.php
<?php
...
function get_attachment_link( $post = null, $leavename = false ) {
global $wp_rewrite;
$link = false;
$post = get_post( $post );
$parent = ( $post->post_parent > 0 && $post->post_parent != $post->ID ) ? get_post( $post->post_parent ) : false;
if ( $parent && ! in_array( $parent->post_type, get_post_types() ) ) {
$parent = false;
}
if ( $wp_rewrite->using_permalinks() && $parent ) {
if ( 'page' == $parent->post_type )
$parentlink = _get_page_link( $post->post_parent ); // Ignores page_on_front
else
$parentlink = get_permalink( $post->post_parent );
if ( is_numeric($post->post_name) || false !== strpos(get_option('permalink_structure'), '%category%') )
$name = 'attachment/' . $post->post_name; // <permalink>/<int>/ is paged so we use the explicit attachment marker
else
$name = $post->post_name;
if ( strpos($parentlink, '?') === false )
$link = user_trailingslashit( trailingslashit($parentlink) . '%postname%' );
if ( ! $leavename )
$link = str_replace( '%postname%', $name, $link );
} elseif ( $wp_rewrite->using_permalinks() && ! $leavename ) {
$link = home_url( user_trailingslashit( $post->post_name ) );
}
if ( ! $link )
$link = home_url( '/?attachment_id=' . $post->ID );
/**
* Filters the permalink for an attachment.
*
* @since 2.0.0
*
* @param string $link The attachment's permalink.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'attachment_link', $link, $post->ID );
}
...
?>
其他
英文文档:https://developer.wordpress.org/reference/functions/get_attachment_link/