• I am attempting to re-write the HTML structure of image tags in WordPress. By default, when an image is uploaded to WP and the photo added to a post, the following code is inserted into the post:

    <img src="url/test-photo.jpg" alt="Alt text here" class="alignright size-full wp-image-168" />

    Is there some way that I can use built-in WP functions to re-write the structure of that html? I would like to add other attributes in to the img tag. I’m guessing there’s maybe a couple ways of doing this…one would be to modify the code that the editor dumps into the post, another would be to capture the content as it’s coming from the database, swap out attributes and then forward that changed code to the browser (aka. parsing the HTML for img tags). This method would utilize the DOMDocument PHP class. Is one option better over another? Does the DOMDocument method add more time than say tweaking how the editor populates/constructs the image tag to begin with?

    Just as an fyi, I am trying to re-write the image tags to look like this:

    <img data-src="url/test-photo.jpg" alt="Alt text here" data-width="{width of photo gets put here}" data-height="{height of photo gets put here}" class="alignright size-full wp-image-168 fs-img" />

    I’m trying to get something like the below function to work. I currently have this function in my theme’s functions.php file. I picked up most of this function from the wp-includes/media.php file.

    add_filter('get_image_tag', 'restructure_imgs', 10, 2);
    function restructure_imgs($html, $id, $alt, $align, $size) {
        list( $img_src, $width, $height ) = image_downsize($id, $size);
        $imagesize = getimagesize($img_src);
    
        $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
        $html = '<img data-src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" data-width="' . $imagesize[0] . '" data-height="' . $imagesize[1] . '" class="' . $class . '" />';
        $before = '<div class="media">';
        $after = '</div>';
        $html = $before . $html . $after;
    
        return $html;
    }

    This is mostly working, but I am having one small problem. I am trying to create ‘data-width’ and ‘data-height’ attributes and populate those with the given image’s width and height values. Unfortunately, when I add an image to a post and inspect the source, my image tag looks something like this:

    <img data-src="url/test-photo.jpg" alt="Alt text here" data-data-class="align size- wp-image-172 fs-img" />

    *Notice the weird “data-data-” broken attributes and the broken “size-” in class. How can I pass in the image width and height? Any thoughts?

  • The topic ‘Trying to re-write image tags in WordPress’ is closed to new replies.