Add a "Credit" field to images in the Media Library, and show it under featured images and in image captions.
add_filter( 'attachment_fields_to_edit', function ( array $fields, WP_Post $post ): array {
if ( ! wp_attachment_is_image( $post ) ) {
return $fields;
}
$fields['nahnu_credit'] = [
'label' => 'Credit',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'nahnu_credit', true ),
'helps' => 'Photographer or source, e.g. "Photo: Jane Doe / Unsplash".',
];
return $fields;
}, 10, 2 );
add_filter( 'attachment_fields_to_save', function ( array $post, array $attachment ): array {
if ( isset( $attachment['nahnu_credit'] ) && current_user_can( 'edit_post', $post['ID'] ) ) {
update_post_meta( $post['ID'], 'nahnu_credit', sanitize_text_field( $attachment['nahnu_credit'] ) );
}
return $post;
}, 10, 2 );
// Show the credit after the featured image on single posts.
add_filter( 'post_thumbnail_html', function ( string $html, int $post_id, $thumbnail_id ): string {
$credit = $thumbnail_id ? get_post_meta( (int) $thumbnail_id, 'nahnu_credit', true ) : '';
if ( '' === $credit || ! is_singular() || $post_id !== get_queried_object_id() ) {
return $html;
}
return $html . '<p class="nahnu-credit"><small>' . esc_html( $credit ) . '</small></p>';
}, 10, 3 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Stock and press photos often need a credit line. Typing it into every caption is easy to forget and hard to keep consistent. This snippet stores the credit with the image itself.
attachment_fields_to_edit adds a Credit field to the image details panel in the Media Library and media picker. attachment_fields_to_save saves it as image meta, cleaned with sanitize_text_field().
post_thumbnail_html adds the credit below the featured image on the post’s own page. It isn’t shown on archives.
get_post_meta( $image_id, 'nahnu_credit', true )..nahnu-credit class.Open an image in the Media Library, fill in Credit and set it as a post’s featured image. The credit should appear under it on the post.