Add custom field to media attachment image attribute in post editor

I wonder if you want to modify the HTML of the inserted image, with the image_send_to_editor or get_image_tag filters?

If that’s the case, then here’s one example:

/**   
 * Add the data-ext-link-title and data-ext-link-url attributes to inserted images. 
 */

add_filter( 'image_send_to_editor',
    function( $html, $id, $caption, $title, $align, $url, $size, $alt )
    {    
        if( $id > 0 )
        {
            $ext_title = get_post_meta( $id, 'pp_external_link_title', true ); 
            $ext_url   = get_post_meta( $id, 'pp_external_link_url',   true ); 
            $data  = sprintf( ' data-ext-link-title="%s" ', esc_attr( $ext_title ) );
            $data .= sprintf( ' data-ext-link-url="%s" ',   esc_url( $ext_url )    );
            $html = str_replace( "<img src", "<img{$data}src", $html );
        }
        return $html;
    }
, 10, 8 );

Here I assume you want empty data-ext-link-title or data-ext-link-url attributes, if the corresponding meta values are empty or missing.

Hopefully you can adjust this to your needs.

Leave a Comment