SYNCER

SYNCER

get_attached_file() - 指定したIDの添付ファイルのフルパスを取得する

公開日:

get_attached_file()は、指定したIDの添付ファイルのフルパスを取得する関数です。

構文

mixed get_attached_file( int $attachment_id, bool $unfiltered = false )

パラメータ

$attachment_id

添付ファイルのIDを数値で指定する。

$unfiltered

初期値: false

フィルターの呼び出しを行わない場合はtrue、行なう場合はfalseを指定する。

返り値

mixed

指定したIDの添付ファイルのフルパスを文字列で返す。指定したIDの添付ファイルが存在しない場合はfalseが返る。

関数

この関数内で利用している、別のWordPress関数です。

フック

関数内で呼び出されるイベントです。

フィルター

get_attached_file - 添付ファイルのフルパスを加工するフィルターイベント。

サンプルコード

添付ファイルのフルパス

ID25の添付ファイル(リンク)のフルパスを取得します。

php

<?php
	// 実行
	$result = get_attached_file( 25 ) ;

	// 結果
	print_r( $result ) ;

結果 (出力内容) - PHP7.0.13

/var/www/syncer.jp/wordpress/public_html/wp-content/uploads/2016/12/2016-10-12-12.46.02.jpg

ソースコード

wp-includes/post.php

/**
 * Retrieve attached file path based on attachment ID.
 *
 * By default the path will go through the 'get_attached_file' filter, but
 * passing a true to the $unfiltered argument of get_attached_file() will
 * return the file path unfiltered.
 *
 * The function works by getting the single post meta name, named
 * '_wp_attached_file' and returning it. This is a convenience function to
 * prevent looking up the meta name and provide a mechanism for sending the
 * attached filename through a filter.
 *
 * @since 2.0.0
 *
 * @param int  $attachment_id Attachment ID.
 * @param bool $unfiltered    Optional. Whether to apply filters. Default false.
 * @return string|false The file path to where the attached file should be, false otherwise.
 */
function get_attached_file( $attachment_id, $unfiltered = false ) {
	$file = get_post_meta( $attachment_id, '_wp_attached_file', true );

	// If the file is relative, prepend upload dir.
	if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) && ( ( $uploads = wp_get_upload_dir() ) && false === $uploads['error'] ) ) {
		$file = $uploads['basedir'] . "/$file";
	}

	if ( $unfiltered ) {
		return $file;
	}

	/**
	 * Filters the attached file based on the given ID.
	 *
	 * @since 2.1.0
	 *
	 * @param string $file          Path to attached file.
	 * @param int    $attachment_id Attachment ID.
	 */
	return apply_filters( 'get_attached_file', $file, $attachment_id );
}

参考リンク