Skip to content

Instantly share code, notes, and snippets.

@aliciaduffy
Created November 19, 2014 18:05
Show Gist options
  • Save aliciaduffy/7a8c88058e1b93d9566b to your computer and use it in GitHub Desktop.
Save aliciaduffy/7a8c88058e1b93d9566b to your computer and use it in GitHub Desktop.
Add media credit below images in content
function filter_images($content){
$original_content = $content;
$inlineImages = array();
// Find all images with an ID in content
preg_match_all( '/wp-image-([^"]*)/i', $content, $inlineImages );
if ($inlineImages) {
// For each image build the credit and add to content
foreach ($inlineImages[1] as $attachment_id) {
if ( have_rows('media_credit', $attachment_id ) ) :
$image_credit = '<div class="credit">';
while( have_rows( 'media_credit', $attachment_id ) ) :
the_row();
$image_credit .= '<span>';
$credit = get_sub_field('credit');
$credit_link = get_sub_field('credit_link');
// If credit is linked, else just display credit
if (!empty($credit_link) && !empty($credit) ) {
$image_credit .= '<a href="'.$credit_link.'">'.$credit.'</a>';
} else {
$image_credit .= $credit;
}
$image_credit .= '</span>';
endwhile;
$image_credit .= '</div>';
// Find image with our ID
$pattern = "/\<img (.*)wp-image-" . $attachment_id . "(.*)>/";
// TODO - MATCH IMAGES WRAPPED IN LINKS - MUST FORMAT DIFFERENT
// $linked_image_pattern = "/<a (.*)><img (.*)wp-image-" . $attachment_id . "(.*)><\/a>/";
// Add credit below image, wrap in <div>
$new_image = '<div class="media-credit"><img ${1}wp-image-' . $attachment_id . '${2}>' . $image_credit . '</div>';
$content = preg_replace($pattern, $new_image, $content);
endif;
}
}
return $content . $original_content;
}
add_filter('the_content', 'filter_images');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment