Thanks again to ACF Support for researching this. They recommended hooking into the function:
image_send_to_editor
https://developer.www.ads-software.com/reference/hooks/image_send_to_editor/
I’m now using the values of two ACF fields that I’ve added to the Insert Image dialog, credit_name and credit_website, to create data attributes for the img tag. Neither field is required, and some photos have the photographer’s name only and no photographer’s website URL. Based on the example in the documentation, here’s the code I came up with:
/**
* Add the data-credit-name and data-credit-website attributes to inserted image tag.
*/
function add_custom_data_attributes_send_to_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ){
if( $id > 0 ){
$post = get_post( $id );
$media_id = $post->ID;
$credit_name = esc_attr(get_field( 'credit_name', $media_id ));
$credit_website = esc_url(get_field( 'credit_website', $media_id ));
$media_data = array(
$post->ID, // media id[0]
$credit_name, // photographer's name or company name
$credit_website // photographer's website URL
);
$data = sprintf( ' data-credit-name="%s"', esc_attr( $media_data[1] ) ); // set data-credit-name
$data .= sprintf( ' data-credit-website="%s" ', esc_url( $media_data[2] ) ); // data-credit-website
$html = str_replace( "<img src", "<img{$data}src", $html ); // replace and add custom attributes
}
return $html;
}
add_filter( 'image_send_to_editor', 'add_custom_data_attributes_send_to_editor', 10, 8 );
And here is the javascript I’m using to create markup to display the information from the data attributes on the page.
/** Add photo credit to photos which have data attributes from ACF and PHP script */
function photoCredit() {
$('#primary img[data-credit-name]').each(function() {
let creditName = $(this).data('credit-name');
let creditWebsite = $(this).data('credit-website');
let imgWidth = $(this).css('width');
let creditMarkup = '';
if ( ($(this).data('credit-website')) && ($(this).data('credit-name')) ) {
creditMarkup = '<div class="photo-credit" style="width:' +imgWidth+ '">Photo by <a href="' + creditWebsite + '" target="_blank">' + creditName + '</a></div>';
} else if ( $(this).data('credit-name') ) {
creditMarkup = '<div class="photo-credit" style="width:' +imgWidth+ '">Photo by ' + creditName + '</div>';
}
$(this).addClass('with-credit').after(creditMarkup);
});
}
photoCredit();
After that it’s just a matter of writing the CSS to style the div.photo-credit
I position it so it is superimposed along the bottom edge of the photo, but it can also go just beneath the photo instead.
I hope this is helpful to someone!