Using WordPress ‘get_image_tag’ PHP filter

The get_image_tag WordPress PHP filter allows you to modify the HTML content of an image tag before it’s displayed on the front-end of your website.

Usage

add_filter('get_image_tag', 'your_custom_function', 10, 6);

function your_custom_function($html, $id, $alt, $title, $align, $size) {
  // your custom code here
  return $html;
}

Parameters

  • $html (string) – HTML content for the image.
  • $id (int) – Attachment ID.
  • $alt (string) – Image description for the alt attribute.
  • $title (string) – Image description for the title attribute.
  • $align (string) – Part of the class name for aligning the image.
  • $size (string|int[]) – Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).

More information

See WordPress Developer Resources: get_image_tag

Examples

Add custom CSS class to image tag

This code adds a custom CSS class my-custom-class to the image tag.

add_filter('get_image_tag', 'add_custom_class_to_image', 10, 6);

function add_custom_class_to_image($html, $id, $alt, $title, $align, $size) {
  $html = str_replace('<img', '<img class="my-custom-class"', $html);
  return $html;
}

Add data attribute to image tag

This code adds a custom data attribute data-custom-attribute with a value custom-value to the image tag.

add_filter('get_image_tag', 'add_data_attribute_to_image', 10, 6);

function add_data_attribute_to_image($html, $id, $alt, $title, $align, $size) {
  $html = str_replace('<img', '<img data-custom-attribute="custom-value"', $html);
  return $html;
}

Remove title attribute from image tag

This code removes the title attribute from the image tag.

add_filter('get_image_tag', 'remove_title_attribute', 10, 6);

function remove_title_attribute($html, $id, $alt, $title, $align, $size) {
  $html = preg_replace('/title="[^"]+"/', '', $html);
  return $html;
}

Modify alt attribute text

This code modifies the alt attribute text by appending custom text to it.

add_filter('get_image_tag', 'modify_alt_text', 10, 6);

function modify_alt_text($html, $id, $alt, $title, $align, $size) {
  $custom_text = ' - Custom Text';
  $html = str_replace('alt="'.$alt.'"', 'alt="'.$alt.$custom_text.'"', $html);
  return $html;
}

Add lazy-loading to image tag

This code adds lazy-loading to the image tag using loading="lazy" attribute.

add_filter('get_image_tag', 'add_lazy_loading', 10, 6);

function add_lazy_loading($html, $id, $alt, $title, $align, $size) {
  $html = str_replace('<img', '<img loading="lazy"', $html);
  return $html;
}