The img_caption_shortcode
example from the WordPress codex is a good skeleton structure to jump off of to add custom fields and adjust the markup to suit your needs.
In the following example, my ACF field is called “photo_credit” and is connected to any image file in the media gallery.
This will allow you to display additional information automatically (similar to a caption).
Targeting a media item
Something to keep in mind when getting custom fields that are attached to something like a media file is that you’ll need to pass a second parameter to target the media it is connected to.
One way of getting this corresponding ID is to use preg_match & regex to split the number off before the $attr are defined in the example below.
/**
* Customize <img> shortcode markup..
*/
add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );
function my_img_caption_shortcode( $empty, $attr, $content ){
preg_match( '/(\d+)$/', $attr['id'], $matches );
$media_id = $matches[1];
$credit = get_field( 'photo_credit', $media_id );
$attr = shortcode_atts( array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'credit' => $credit,
'caption' => '',
), $attr );
if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
return '';
}
if ( $attr['id'] ) {
$attr['id'] = 'id="' . esc_attr( $attr['id'] ) . '" ';
}
return '<div ' . $attr['id']
. 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" style="max-width: ' . ( 10 + (int) $attr['width'] ) . 'px;">'
. do_shortcode( $content )
. '<p class="wp-caption-text">' . $attr['caption'] . '</p><p class="photo-credit">' . $attr['credit'] . '</p></div>';
}
Additional Reading:
- WordPress Codex: img_caption_shortcode
- ACF Docs: Adding fields to media attachments
- php Docs: preg_match
This is exactly what I needed.
I’m shocked that there isn’t a well-developed plugin to handle an image credit use-case. But this code was easy enough and worked exactly as expect.
Now to style it with css!
Exactly what I searched for. Thank you. Unfortunately it seems img_caption_shortcode (as well as image_send_to_editor) does not work with Gutenberg anymore. Do you know a way to get this working with Gutenberg? Cheers, Alf