apply_filters( 'wp_get_attachment_image_attributes', array $attr , WP_Post $attachment , string|array $size )
Filters the list of attachment image attributes.
Description Description
Parameters Parameters
- $attr
-
(array) Attributes for the image markup.
- $attachment
-
(WP_Post) Image attachment post.
- $size
-
(string|array) Requested size. Image size or array of width and height values (in that order). Default 'thumbnail'.
Source Source
File: wp-includes/media.php
Changelog Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
Add a data attribute to each <img> tag in a gallery
Note: this filter runs inside
wp_get_attachment_image(), which means your attribute will be added for all uses of the function./** * Filter attributes for the current gallery image tag to add a 'data-full' * data attribute. * * @param array $atts Gallery image tag attributes. * @param WP_Post $attachment WP_Post object for the attachment. * @return array (maybe) filtered gallery image tag attributes. */ function wpdocs_filter_gallery_img_atts( $atts, $attachment ) { if ( $full_size = wp_get_attachment_image_src( $attachment->ID, 'full' ) ) { if ( ! empty( $full_size[0] ) ) { $atts['data-full'] = $full_size[0]; } } return $atts; } add_filter( 'wp_get_attachment_image_attributes', 'wpdocs_filter_gallery_img_atts', 10, 2 );Expand full source codeCollapse full source code
/** * Add classes to the cutom logo. */ add_filter( 'wp_get_attachment_image_attributes', function ( $attr ) { if ( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] ) { $attr['class'] = 'custom-logo foo-bar NEW CLASSES HERE'; } return $attr; } );This only seems to fire for featured images. At least, it’s the experience of this person on Stack Exchange, and of myself.
https://wordpress.stackexchange.com/questions/266702/wp-get-attachment-image-attributes-not-working-for-me
You can add custom data attributes to image elements by adding this snippet on theme’s function.php:
/** * Add custom data attribute to every image element */ add_filter( 'wp_get_attachment_image_attributes', 'add_custom_image_data_attributes', 10, 3 ); function add_custom_image_data_attributes( $attr, $attachment, $size ) { // Ensure that the <img> doesn't have the data attribute already if ( ! array_key_exists( 'data-custom', $attr ) ) { $attr['data-custom'] = 'dummy text'; } return $attr; }Expand full source codeCollapse full source code
Also, note that I use
array_key_exists()PHP function instead ofisset()becauseisset()does not return TRUE for array keys that correspond to a NULL value, whilearray_key_exists()does as of PHP Manual (http://php.net/manual/en/function.array-key-exists.php).