I’ve added two custom fields to attachments on my site, so the user can add a special image credit.
I’m trying to write a function that looks to see if either of the custom fields are populated, and if so echoes the contents.
The part I’m struggling with is getting the ID of the image into the function – it’s simple enough for featured images using get_post_thumbnail_id()
– is there a similar way to get the ID for any attached image?
Here’s what I have so far:
function mat_image_credit() {
//this is the bit I'm struggling with:
$mat_image_id = wp_get_attachment_image( $attachment->ID );
//this is collecting the contents of the custom field and works fine
$mat_flickr_credit = slt_cf_field_value('flickr_credit', 'attachment', $mat_image_id);
$mat_custom_credit = slt_cf_field_value('custom_credit', 'attachment', $mat_image_id);
//and then this echoes out the contents depending on what we find...
if (!empty ( $mat_flickr_credit ) ) {
echo '<div class="credit">Image by <a href="http://www.flickr.com/photos/' . $mat_flickr_credit . '" target="blank">' . $mat_flickr_credit . '</a></div>';
} elseif ( !empty ( $mat_custom_credit ) ) {
echo '<div class="credit">Image by ' . $mat_custom_credit . '</div>';
};
}
Thanks!
Hopefully this helps,
Then in your theme (used within The Loop),
The
foreach
statement is making the assumption that users can attach more than one image and credit attributions per post and that you want them printed in some kind of grouped order.The alternative is to do away with the foreach statement and instead pluck the first image from the array of returned attachments,
Then in your theme [same as before] (used within The Loop),
Beyond this you could extend this function to make it a little dynamic in the sense that you could grab the first, second and third image attachments and use them in different parts of your template.
Example;
Then in your theme [same as before] (used within The Loop),
If you don’t specify a value (integer) then the function by default will assign
0
as the key, which would retrieve the first image in the array of results. Subsequently, for those in which you specify an value, the correspondingkey => value
will be retrieved.Who knows… you might need to retrieve more than one lot of credits in more than one place in a template file. This will help.
I went about it like this in the end:
Then in my template I can just