ACF File attachment display

Hello,

I’m trying to display a dynamic list of attachments to a post that loops through an ACF file field. I have it pretty close, but its giving an additional error along with the output and I’m not quite sure why.


image

I’m guessing this is something related to the script, but I’m not much of a coder, so I’m not sure where to look here. PHP version is 8.1.

I’ve tried to follow this as well for some guideance, but the formatting of the php within the builder doesn’t appear to allow me to use the same syntax as in the video.

Hi,

here you can read how to access a value of type File (see the section ‘Advanced display (array)’) ACF | File

Afaik the field-type you are using can only contain one File, so the field-label and field-name ‘attachments’ are misleading. If you want to attach multiple files i think you would need a repeater-field with an field-upload-field in it.

I also don’t understand where the field-name ‘field_64ff9a11156c4’ in your code is coming from, for in the screenshot, the field-name is ‘attachements’.

Br

Tobias

So, yea, the field name is misleading, but yes, I understand it’s a singular file unless in a repeater of course. But just need 1. So, the code I am using is correct, but I’m not sure why the error is included. The field name is the only one that pulls the data as shown here. To also clarify, the field is a sub-field of a ‘group’, so its not a top level field within the field group itself.


Would it be better practice to remove it from the group?
I mean, it is grabbing the fields.

Any better suggestions on how to acheive this? Maybe I’m just ignorant of how to best do this…

Hi

can you change the return type of the ACF field attachments to URL and use this code:

<?php if( get_field('attachments') ): ?>
    <a href="<?php the_field('attachments'); ?>" >Download File</a>
<?php endif; ?>

Does it also show an error?

Cheers

Patric

Thank you for the clarification! I didn’t know that it’s possible for the get_field function to use the name or the key for getting an acf-field. So I learned something new here.

So indeed you can use the field-key as you did. However it seems that the field-key you used ‘field_64ff9a11156c4’ is NOT the key of the attachment-field, as you can see in the screenshot (I guess it’s the group-key).

You can do the following:

// i still would suggest renaming the field to attachment
$attachment = get_field('field_64ff99ab156c3'); // or get_field('attachments');
$url = $attachment['url'];
$title = $attachment['title'];

//for it's just a single item you don't need a list-element
echo '<a href="' . $url . '">'. $title . '</a>'; 

Br

Tobias

This sort of does, but it shows returns all the array fields in the link.

This solution works…

<?php
$file = get_field('attachment');
if( $file ): ?>
    <a href="<?php echo $file['url']; ?>" target="_blank"><?php echo $file['filename']; ?></a><br>
<?php endif; ?>
1 Like