wp_get_attachment_url()

wp_get_attachment_url( int $attachment_id ) 检索附件的URL。 R…

wp_get_attachment_url( int $attachment_id )

检索附件的URL。
Retrieve the URL for an attachment.

目录锚点:#参数#源码#笔记


参数(Parameters)

参数 类型 说明
$attachment_id (int) 附件帖子ID。默认为全局$post。

源码(Source)

/**
 * Retrieve the URL for an attachment.
 *
 * @since 2.1.0
 *
 * @global string $pagenow
 *
 * @param int $post_id Optional. Attachment ID. Default 0.
 * @return string|false Attachment URL, otherwise false.
 */
function wp_get_attachment_url( $post_id = 0 ) {
	$post_id = (int) $post_id;
	if ( !$post = get_post( $post_id ) )
		return false;

	if ( 'attachment' != $post->post_type )
		return false;

	$url = '';
	// Get attached file.
	if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) {
		// Get upload directory.
		if ( ($uploads = wp_upload_dir()) && 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') ) {
				$url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
			} 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 ( empty($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 );
	}

	/**
	 * Filter the attachment URL.
	 *
	 * @since 2.1.0
	 *
	 * @param string $url     URL for the given attachment.
	 * @param int    $post_id Attachment ID.
	 */
	$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );

	if ( empty( $url ) )
		return false;

	return $url;
}
更新版本 源码位置 使用 被使用
2.1.0 wp-includes/post.php 3 9

笔记(Notes)

使用后缩略图作为背景图像

类别:WordPress 函数手册

本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

评论 (0)COMMENT

登录 账号发表你的看法,还没有账号?立即免费 注册