Using WordPress ‘get_attachment_taxonomies()’ PHP function

The get_attachment_taxonomies() WordPress PHP function retrieves taxonomies attached to a given attachment.

Usage

get_attachment_taxonomies($attachment, $output = 'names');

Parameters

  • $attachment (int|array|object): Required. The attachment ID, data array, or data object.
  • $output (string): Optional. The output type. Use ‘names’ to return an array of taxonomy names, or ‘objects’ to return an array of taxonomy objects. Default is ‘names’.

More information

See WordPress Developer Resources: get_attachment_taxonomies()

Examples

Retrieve taxonomy names attached to an attachment

In this example, we will retrieve the taxonomy names attached to an attachment with ID 123.

$attachment_id = 123;
$taxonomies = get_attachment_taxonomies($attachment_id);
print_r($taxonomies);

Retrieve taxonomy objects attached to an attachment

In this example, we will retrieve the taxonomy objects attached to an attachment with ID 123.

$attachment_id = 123;
$taxonomies = get_attachment_taxonomies($attachment_id, 'objects');
print_r($taxonomies);

Retrieve taxonomy names from an attachment object

In this example, we will retrieve the taxonomy names from an attachment object.

$attachment = get_post(123);
$taxonomies = get_attachment_taxonomies($attachment);
print_r($taxonomies);

Retrieve taxonomy objects from an attachment object

In this example, we will retrieve the taxonomy objects from an attachment object.

$attachment = get_post(123);
$taxonomies = get_attachment_taxonomies($attachment, 'objects');
print_r($taxonomies);

Retrieve taxonomies attached to an attachment using a custom loop

In this example, we will retrieve the taxonomies attached to an attachment in a custom loop.

$args = array(
    'post_type' => 'attachment',
    'posts_per_page' => 10,
);
$attachments = get_posts($args);

foreach ($attachments as $attachment) {
    $taxonomies = get_attachment_taxonomies($attachment);
    echo "Attachment ID: " . $attachment->ID . "\n";
    echo "Taxonomies: ";
    print_r($taxonomies);
    echo "\n\n";
}