get_attachment_taxonomies() WordPress Function

The get_attachment_taxonomies() function retrieves all taxonomies associated with an attachment. This function is useful for retrieving information about an attachment, such as its categories or tags.

get_attachment_taxonomies( int|array|object $attachment, string $output = 'names' ) #

Retrieves taxonomies attached to given the attachment.


Parameters

$attachment

(int|array|object)(Required)Attachment ID, data array, or data object.

$output

(string)(Optional)Output type. 'names' to return an array of taxonomy names, or 'objects' to return an array of taxonomy objects. Default is 'names'.

Default value: 'names'


Top ↑

Return

(string[]|WP_Taxonomy[]) List of taxonomies or taxonomy names. Empty array on failure.


Top ↑

Source

File: wp-includes/media.php

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 = wp_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 ) {
		$taxes = get_object_taxonomies( $object, $output );

		if ( $taxes ) {
			$taxonomies = array_merge( $taxonomies, $taxes );
		}
	}

	if ( 'names' === $output ) {
		$taxonomies = array_unique( $taxonomies );
	}

	return $taxonomies;
}


Top ↑

Changelog

Changelog
VersionDescription
4.7.0Introduced the $output parameter.
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More