Okay, I’ve been working on this all day and can’t find the solution anywhere. I’ve created a custom field within the image upload screen (info first found here). The field stores the name of a photographer to give him/her credit. Everything’s fine there.
What I can’t figure out is how to get this information into every image’s title data across the site. I want my field for Image Credit to append itself to all image titles across the site, so each image title would read something like “My Title (by Photographer Name)”.
What I have figured out is close, but not quite good enough. I can get the information from my custom field by using “get_children()” of type “image” on the existing post, and then calling “get_post_meta()” for my custom field name on each result. I can then use this information to add it to the post featured images by altering the title properties within “get_the_post_thumbnail()” when I call it. What I need is to be able to do something like this site-wide on all images, not just the featured ones.
I feel like there should be somewhere in the Core that defines how images are displayed. Perhaps I could overwrite this with a same-name file in my own theme, or by declaring a function to override the default behavior. Maybe there’s a filter or a hook I could use. However, I can’t find any documentation to help me, and I’m about out of ideas.
Any and all thoughts would be much appreciated, even if they’re just partial ideas.
Note: I tried to link all my functions for easy reference, but spam-prevention wouldn’t let me post that many links so I’ll list them here instead:
- codex.wordpress.org/Function_Reference/get_children
- codex.wordpress.org/Function_Reference/get_post_meta
- codex.wordpress.org/Function_Reference/get_the_post_thumbnail
2 Answers
You can create a filter using the “wp_get_attachment_image_attributes” hook. Place this in your functions.php file.
function filter_image_title($attr, $attachment = null){
//Find your $photographer with $attachment->ID
$attr['title'] .= ' (' . __('Photographed by', 'foobar') . ' ' . $photographer . ')';
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'filter_image_title', 10, 2);