Alter image output in content

I’m trying to implement the JAIL javascript into my WordPress install. The javascript requires me to add a data-attribute and change the output html of images.

I have been looking through the codex for filters or hooks that can help me, but i can’t find anything. Anyone have a solution?

Related posts

Leave a Reply

1 comment

  1. Your better off adding your custom image data when you insert it into a post using media_send_to_editor, the caveat is this will not be applied to any existing images, only ones inserted after adding the function.

    To apply it to to existing content you will have use preg_match on the_content filter, but this can significantly slow your site down, it is advised you don’t parse the output like this.

    A media_send_to_editor example:

    function WPSE_78285_Mime($html, $id) {
    
        //fetching attachment by post $id
        $attachment = get_post($id); 
        $mime_type = $attachment->post_mime_type;
    
        //get an valid array of images types   
        $image_exts = array( 'image/jpg', 'image/jpeg', 'image/jpe', 'image/gif', 'image/png' );
    
        //checking the above mime-type
        if (in_array($mime_type, $image_exts)) { 
    
            // the image link would be great
            $src = wp_get_attachment_url( $id );
    
            // enter you custom output here, you will want to probably change this
            $html = '<a href="' . $src .  '" class="your-class" data-src="/img/image1.jpg" rel="your-rel"><img src="'. $src .'" /></a>';
            return $html; // return new $html    
        }
            return $html;
    }
    
    add_filter('media_send_to_editor', 'WPSE_78285_Mime', 20, 2);