函数
wp_get_attachment_url( $id );
描述
该WordPress函数可获取附件的url
参数
参数 | 数据类型 | 是否必需 | 描述 | 默认值 |
---|---|---|---|---|
$id | 整数 | 是 | 附件ID | 无 |
返回值
返回附件文件的完整 URI,如果获取失败,返回 false。
划重点
可以通过使用 wp_get_attachment_url_filter
修改函数的输出。
此函数将不会 urlencode
获取到的 url
,如果附件文件名有不合法的字符串,我们需要使用编码输出的内容以获取一个正确的url
。
如果需要一个附件页面的 URI ,而不是附件文件,我们可以使用 get_attachment_link
函数。
实例
获取附件id为2048的附件链接
echo wp_get_attachment_url( 2048 );
修改记录
WordPress 2.1.0
源文件
wp-includes/post.php
function wp_get_attachment_url( $attachment_id = 0 ) { $attachment_id = (int) $attachment_id; $post = get_post( $attachment_id ); if ( ! $post ) { return false; } if ( 'attachment' !== $post->post_type ) { return false; } $url = ''; // Get attached file. $file = get_post_meta( $post->ID, '_wp_attached_file', true ); if ( $file ) { // Get upload directory. $uploads = wp_get_upload_dir(); if ( $uploads && false === $uploads['error'] ) { // Check that the upload base exists in the file location. if ( 0 === strpos( $file, $uploads['basedir'] ) ) { // Replace file location with url location. $url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file ); } elseif ( false !== strpos( $file, 'wp-content/uploads' ) ) { // Get the directory name relative to the basedir (back compat for pre-2.7 uploads). $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . wp_basename( $file ); } else { // It's a newly-uploaded file, therefore $file is relative to the basedir. $url = $uploads['baseurl'] . "/$file"; } } } /* * If any of the above options failed, Fallback on the GUID as used pre-2.7, * not recommended to rely upon this. */ if ( ! $url ) { $url = get_the_guid( $post->ID ); } // On SSL front end, URLs should be HTTPS. if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) { $url = set_url_scheme( $url ); } /** * Filters the attachment URL. * * @since 2.1.0 * * @param string $url URL for the given attachment. * @param int $attachment_id Attachment post ID. */ $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID ); if ( ! $url ) { return false; } return $url; }
本文由 猫斯基 原创发布。
著作权均归用户本人所有。独家文章转载,请联系本站管理员。获得授权后,须注明本文地址! 本文地址:https://maosiji.com/wordpress/wordpress-wp_get_attachment_url.html