Support

Account

Home Forums ACF PRO Displaying custom field on all attached media items

Solving

Displaying custom field on all attached media items

  • So using the Forms -> Attachment location rule you can add data associated to a media item. Is there a reasonable way to display that information on the site automatically when an image is added to a post or page?

    The use case I’m working on here is: All/most photos will have a caption that is going to by styled very specifically. The designs, however, also allow for optional photo credits when required by licenses that are styles outside of the photo caption. I’ve added a new field to the attachment form to collect photo credit, but how can I hook that to WordPress so that the photo credit is displayed when an image is added to a page? I’d like something a little more elegant for our editors than having to wrap part of the caption in <span> tags to be styled with negative margins and/or absolute positioning.

  • Hi @aswhipple

    It depends on how you add the image. If you use WordPress content editor, then you need to check the content for any attachment link because WordPress attach the attachment just like a normal link. After that, you need to get the ID of the attachment from the link. Then you can show the custom field value by following this guide: https://www.advancedcustomfields.com/resources/how-to-get-values-from-a-media-attachment/.

    The important thing is to get the attachment ID so you can get the custom field value by using that ID.

    I hope this makes sense 🙂

  • It does! I tracked down that guide and it definitely breaks down the display well, but I’m now wondering what the best way is to hook into WordPress’s default display of images. I’ve modified the way the caption shortcode works to change that output before, but I’ll need this to spit out available photo credits for images with or without captions, so messing with caption shortcode won’t help.

  • Hi @aswhipple

    I think you can use the the_content filter and try to find the attachment URL. After that, you need to convert this URL to the attachment ID. Here’s an example how to do that: http://wordpress.stackexchange.com/questions/6645/turn-a-url-into-an-attachment-post-id.

    After you got the attachment ID, you can use the get_field() or the_field() function and replace the image by using the preg_replace() function.

    I’m afraid I can’t give you more details as it needs an advanced code. I’m sorry about that.

    I hope this helps 🙂

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Displaying custom field on all attached media items’ is closed to new replies.