get_attachment_link()
最后更新于:2021-11-26 04:41:16
get_attachment_link( int|object$post=null, bool$leavename=false)Retrieves the permalink for an attachment.
参数
- $post
-
(int|object) (Optional) Post ID or object. Default uses the global
$post
.Default value: null
- $leavename
-
(bool) (Optional) Whether to keep the page name.
Default value: false
响应
(string) The attachment permalink.
源文件
文件: gc-includes/link-template.php
function get_attachment_link( $post = null, $leavename = false ) {
global $gc_rewrite;
$link = false;
$post = get_post( $post );
$force_plain_link = gc_force_plain_post_permalink( $post );
$parent_id = $post->post_parent;
$parent = $parent_id ? get_post( $parent_id ) : false;
$parent_valid = true; // Default for no parent.
if (
$parent_id &&
(
$post->post_parent === $post->ID ||
! $parent ||
! is_post_type_viewable( get_post_type( $parent ) )
)
) {
// Post is either its own parent or parent post unavailable.
$parent_valid = false;
}
if ( $force_plain_link || ! $parent_valid ) {
$link = false;
} elseif ( $gc_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 ( $gc_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
* @since 5.6.0 Providing an empty string will now disable
* the view attachment page link on the media modal.
*
* @param string $link The attachment's permalink.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'attachment_link', $link, $post->ID );
}
<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 ) { echo '<li>'; the_attachment_link( $attachment->ID, true ); echo '<p>'; echo apply_filters( 'the_title', $attachment->post_title ); echo '</p></li>'; } } endwhile; endif; ?> </ul>