Using WordPress ‘get_attachment_template()’ PHP function

The get_attachment_template() WordPress PHP function retrieves the path of an attachment template in the current or parent theme.

Usage

get_attachment_template()

Example:

Input:

$template_path = get_attachment_template();

Output:

/your-theme/image.php

Parameters

  • None

More information

See WordPress Developer Resources: get_attachment_template()

Examples

Display the attachment template path

This example retrieves the attachment template path and displays it:

$template_path = get_attachment_template();
echo 'Attachment Template Path: ' . $template_path;

Include the attachment template

This example includes the attachment template in your theme:

$template_path = get_attachment_template();
include($template_path);

Customize the attachment template path

This example filters the attachment template path to use a custom directory:

add_filter('attachment_template', 'my_custom_attachment_template');
function my_custom_attachment_template($template) {
  return 'custom-directory/' . basename($template);
}

Check if attachment template exists

This example checks if the attachment template exists before using it:

$template_path = get_attachment_template();
if (file_exists($template_path)) {
  include($template_path);
} else {
  echo 'Attachment template not found';
}

Modify the attachment template hierarchy

This example modifies the attachment template hierarchy to include a new template:

add_filter('attachment_template_hierarchy', 'my_custom_attachment_hierarchy');
function my_custom_attachment_hierarchy($templates) {
  array_unshift($templates, 'custom-attachment.php');
  return $templates;
}