Add custom field to media attachment image attribute in post editor

I have the following filter, but do not know how to add custom attributes to image field, when attaching media to post.

example

<img data-ext-link-title="" data-ext-link-url="">

functions.php

function pp_external_link_edit( $form_fields, $post ) {
    $form_fields['pp-external-link-title'] = array(
        'label' => 'External Link Title',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'pp_external_link_title', true ),
        'helps' => 'Link for button at bottom of pretty photo modal',
    );

    $form_fields['pp-external-link-url'] = array(
        'label' => 'External Link URL',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'pp_external_link_url', true ),
        'helps' => 'Link for button at bottom of pretty photo modal',
    );

    return $form_fields;
}

add_filter( 'attachment_fields_to_edit', 'pp_external_link_edit', 10, 2 );

function pp_external_link_save( $post, $attachment ) {
    if( isset( $attachment['pp-external-link-title'] ) )
        update_post_meta( $post['ID'], 'pp_external_link_title', $attachment['pp-external-link-title']);

    if( isset( $attachment['pp-external-link-url'] ) )
        update_post_meta( $post['ID'], 'pp_external_link_url', $attachment['pp-external-link-url']);

    return $post;
}

add_filter( 'attachment_fields_to_save', 'pp_external_link_save', 10, 2 );

2 Answers
2

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