I'm trying to add a filter to the_content that will find all images in the post and append the custom attachment metadata credit to it.

Here's the functions I've have:

Adds the Credit field to attachment details page: (this works)

function attachment_field_credit( $field, $post ) {
    $field[ 'credit' ] = array(
        'label' => 'Credit',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'credit', true ),
    return $field;

Saves the Credit field: (this works)

function attachment_field_credit_save( $post, $attachment ) {
    if( isset( $attachment[ 'credit' ] ) )
        update_post_meta( $post[ 'ID' ], 'credit', $attachment[ 'credit' ] );
    return $post;

Search the content for all available images: (this works)

function find_images( $content ) {
    return preg_replace_callback( '/(<\s*img[^>]+)(src\s*=\s*"[^"]+")([^>]+>)/i', array( $this, 'attach_image_credit' ), $content );

Appends credit metadata to each image: (this doesn't work)

function attach_image_credit( $images ) {
    global $post;
    $credit = get_post_meta( $post->ID, 'credit', true );
    $replacement = $images[0] . $credit;
    return $replacement;

If I replace $credit value with <span>Hello World!</span> the text will be displayed on the page as intended. There must be something wrong with the way I'm trying to get_the_meta value for credit.


If I manually replace:

get_post_meta( $post->ID, 'credit', true );


get_post_meta( 446, 'credit', true );

It works! So all I need to do is to figure out a way to get the attachment ID.

1 Answer 1


Because the credit data is saved in the attachment's post meta, not the main post:

$credit = get_post_meta( $post->ID /* Wrong ID! */, 'credit', true );

Instead you need to catch the ID of the inserted image:

function attach_image_credit( $images ) {
    $return = $images[0];

    // Get the image ID from the unique class added by insert to editor: "wp-image-ID"
    if ( preg_match( '/wp-image-([0-9]+)/', $return, $match ) ) {
        if ( $credit = get_post_meta( $match[1] /* Captured image ID */, 'credit', true ) )
            $return .= $credit;

    return $return;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.