Photo Credit Field for Images
Adds a "Photo credit" field to images in the Media Library and prints the credit under the image whenever it is used in an Image block.
Opens WPIDE on
Code
add_filter( 'attachment_fields_to_edit', function ( $fields, $post ) {
if ( wp_attachment_is_image( $post ) ) {
$fields['wpide_photo_credit'] = array(
'label' => 'Photo credit',
'input' => 'text',
'value' => get_post_meta( $post->ID, '_wpide_photo_credit', true ),
'helps' => 'Shown below the image, for example "Jane Doe / Unsplash".',
);
}
return $fields;
}, 10, 2 );
add_filter( 'attachment_fields_to_save', function ( $post, $attachment ) {
if ( isset( $attachment['wpide_photo_credit'] ) && current_user_can( 'edit_post', $post['ID'] ) ) {
$credit = sanitize_text_field( $attachment['wpide_photo_credit'] );
if ( '' === $credit ) {
delete_post_meta( $post['ID'], '_wpide_photo_credit' );
} else {
update_post_meta( $post['ID'], '_wpide_photo_credit', $credit );
}
}
return $post;
}, 10, 2 );
add_filter( 'render_block_core/image', function ( $content, $block ) {
$id = isset( $block['attrs']['id'] ) ? (int) $block['attrs']['id'] : 0;
$credit = $id ? get_post_meta( $id, '_wpide_photo_credit', true ) : '';
if ( '' === $credit ) {
return $content;
}
$html = '<small class="wpide-photo-credit" style="display:block;font-size:.75em;opacity:.7;">Photo: ' . esc_html( $credit ) . '</small>';
$position = strrpos( $content, '</figure>' );
return false === $position ? $content . $html : substr_replace( $content, $html, $position, 0 );
}, 10, 2 );
Notes
The credit is added below Image blocks that point to the attachment; classic editor images are not changed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.