Using WordPress ‘attachment_innerHTML’ PHP filter

The attachment_innerHTML WordPress PHP filter allows you to modify the HTML content of an attachment displayed on your website.

Usage

add_filter('attachment_innerHTML', 'your_custom_function_name');
function your_custom_function_name($content) {
    // your custom code here
    return $content;
}

Parameters

  • $content (string) – The HTML content of the attachment that you can modify.

More information

See WordPress Developer Resources: attachment_innerHTML

Examples

Add a custom CSS class to attachment images

Add a custom CSS class to images in the attachment content.

add_filter('attachment_innerHTML', 'add_custom_css_class_to_attachment_images');
function add_custom_css_class_to_attachment_images($content) {
    $content = str_replace('<img ', '<img class="custom-class" ', $content);
    return $content;
}

Wrap attachment images in a div

Wrap images in the attachment content with a div.

add_filter('attachment_innerHTML', 'wrap_attachment_images_in_div');
function wrap_attachment_images_in_div($content) {
    $content = preg_replace('/(<img[^>]+>)/', '<div class="image-wrapper">$1</div>', $content);
    return $content;
}

Add a caption to attachment images

Add a caption to images in the attachment content.

add_filter('attachment_innerHTML', 'add_caption_to_attachment_images');
function add_caption_to_attachment_images($content) {
    $content = preg_replace_callback('/(<img[^>]+alt="([^"]*)"[^>]*>)/', function ($matches) {
        return $matches[1] . '<div class="image-caption">' . esc_html($matches[2]) . '</div>';
    }, $content);
    return $content;
}

Remove all attachment images

Remove all images from the attachment content.

add_filter('attachment_innerHTML', 'remove_attachment_images');
function remove_attachment_images($content) {
    $content = preg_replace('/<img[^>]+\>/', '', $content);
    return $content;
}

Replace attachment images with a placeholder

Replace all images in the attachment content with a placeholder image.

add_filter('attachment_innerHTML', 'replace_attachment_images_with_placeholder');
function replace_attachment_images_with_placeholder($content) {
    $placeholder_url = 'https://example.com/placeholder.jpg';
    $content = preg_replace('/(<img[^>]+src=")[^"]*("[^>]*>)/', '$1' . $placeholder_url . '$2', $content);
    return $content;
}