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
.
UPDATE
If I manually replace:
get_post_meta( $post->ID, 'credit', true );
with:
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.