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'.


Top ↑

Source Source

File: wp-includes/media.php

View on Trac


Top ↑

Changelog Changelog

Changelog
Version Description
2.8.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Drew Jaynes

    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 );
    
  2. Skip to note content
    Contributed by Akis

    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;
        }
    

    Also, note that I use array_key_exists() PHP function instead of isset() because isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does as of PHP Manual (http://php.net/manual/en/function.array-key-exists.php).

You must log in before being able to contribute a note or feedback.