Media PHP Intermediate

Add a Photo Credit Field to Media

Add a "Credit" field to images in the Media Library, and show it under featured images and in image captions.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 28 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Images inserted into posts don’t show the credit automatically. Add it to the caption, or read it in your theme with get_post_meta( $image_id, 'nahnu_credit', true ).
  • Style the line with the .nahnu-credit class.

How to test it

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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only