The get_image_tag_class WordPress PHP filter modifies the CSS class attribute for an attachment’s image tag.
Usage
add_filter('get_image_tag_class', 'your_custom_function', 10, 4); function your_custom_function($class, $id, $align, $size) { // your custom code here return $class; }
Parameters
$class
(string) – CSS class name or space-separated list of classes.$id
(int) – Attachment ID.$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_class
Examples
Add a custom class to image tag
Add a custom CSS class named ‘my-custom-class’ to the image tag.
add_filter('get_image_tag_class', 'add_custom_image_class', 10, 4); function add_custom_image_class($class, $id, $align, $size) { $class .= ' my-custom-class'; return $class; }
Remove alignment classes from image tag
Remove any alignment class from the image tag.
add_filter('get_image_tag_class', 'remove_alignment_classes', 10, 4); function remove_alignment_classes($class, $id, $align, $size) { $class = preg_replace('/\balign[a-z]+\b/', '', $class); return $class; }
Add a custom class based on image size
Add a custom CSS class based on the requested image size.
add_filter('get_image_tag_class', 'add_size_based_class', 10, 4); function add_size_based_class($class, $id, $align, $size) { $class .= ' size-' . $size; return $class; }
Add a custom class based on attachment ID
Add a custom CSS class based on the attachment ID.
add_filter('get_image_tag_class', 'add_id_based_class', 10, 4); function add_id_based_class($class, $id, $align, $size) { $class .= ' attachment-id-' . $id; return $class; }
Add a custom class for specific image size
Add a custom CSS class named ‘large-image’ only for images with the ‘large’ size.
add_filter('get_image_tag_class', 'add_class_for_large_images', 10, 4); function add_class_for_large_images($class, $id, $align, $size) { if ($size === 'large') { $class .= ' large-image'; } return $class; }