Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.