get_attachment_taxonomies() - 指定した添付ファイルで利用できるタクソノミーを取得する
公開日:
get_attachment_taxonomies()
は、指定した添付ファイルで利用できるタクソノミーの一覧を、配列で取得する関数です。
構文
array get_attachment_taxonomies( int|array|object $attachment, string $output = 'names' )
パラメータ
$attachment
添付ファイルの種類をID、またはオブジェクトで指定する。複数ある場合は配列で指定する。
$output
初期値: 'names'
返り値の形式を指定する。デフォルト("names"
)ではタクソノミー名の配列が返る。"objects"
を指定すると、タクソノミーオブジェクトの配列が返る。
- "names"
- タクソノミー名の配列。
- "objects"
- タクソノミーオブジェクトの配列。
返り値
array
指定した添付ファイルで利用できるタクソノミーの一覧を配列にした値が返る。各要素は、第2引数の値が"names"
(初期値)の場合は文字列、"objects"
の場合はオブジェクトとなる。
関数
この関数内で利用している、別のWordPress関数です。
- foreach()
- get_attached_file() - 添付ファイルのフルパスを取得する。
- get_post()
サンプルコード
添付ファイルを分類するためのタクソノミー
ID25の添付ファイル(リンク)で利用できるタクソノミーの一覧を取得してみます。が、デフォルトでは添付ファイルを分類するためのタクソノミーが用意されていないため、空の配列が返るはずです。
php
<?php
// 実行
$result = get_attachment_taxonomies( 25 ) ;
// 結果
var_dump( $result ) ;
結果 (出力内容) - PHP7.0.13
array(0) {
}
ソースコード
wp-includes/media.php
/**
* Retrieves taxonomies attached to given the attachment.
*
* @since 2.5.0
* @since 4.7.0 Introduced the `$output` parameter.
*
* @param int|array|object $attachment Attachment ID, data array, or data object.
* @param string $output Output type. 'names' to return an array of taxonomy names,
* or 'objects' to return an array of taxonomy objects.
* Default is 'names'.
* @return array Empty array on failure. List of taxonomies on success.
*/
function get_attachment_taxonomies( $attachment, $output = 'names' ) {
if ( is_int( $attachment ) ) {
$attachment = get_post( $attachment );
} elseif ( is_array( $attachment ) ) {
$attachment = (object) $attachment;
}
if ( ! is_object($attachment) )
return array();
$file = get_attached_file( $attachment->ID );
$filename = basename( $file );
$objects = array('attachment');
if ( false !== strpos($filename, '.') )
$objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
if ( !empty($attachment->post_mime_type) ) {
$objects[] = 'attachment:' . $attachment->post_mime_type;
if ( false !== strpos($attachment->post_mime_type, '/') )
foreach ( explode('/', $attachment->post_mime_type) as $token )
if ( !empty($token) )
$objects[] = "attachment:$token";
}
$taxonomies = array();
foreach ( $objects as $object ) {
if ( $taxes = get_object_taxonomies( $object, $output ) ) {
$taxonomies = array_merge( $taxonomies, $taxes );
}
}
if ( 'names' === $output ) {
$taxonomies = array_unique( $taxonomies );
}
return $taxonomies;
}
参考リンク
- WordPress 関数リファレンス - 公式マニュアル。