DEV Community

WPLake
WPLake

Posted on • Originally published at wplake.org on

About the ACF File field. How to use and display

cover

This article is about the ACF File field, you’ll learn how to use it and the available options. You’ll also learn two ways to display the field, one of them without coding at all. We’ll share how the field works behind the scenes.

About the File field type

The File field is one of many ACF field types, it allows you to “add” attachments from the Media Library to any page.

In case you want to create a link to an external url or internal page you need to use the ACF Link field instead of the File field, you can read more in this article about the ACF Link field.

Unlike the Image field, that only allows images to be selected (.png, .jpg, .gif and such) the File field allows you to choose a file with any extension from your Media Library, including various file types, like .pdf and .doc.

Also, unlike the Image field it doesn’t provide a preview of the selected file, so you can only see the File Name and the File Size. Usually this field type is used to create a download or “open” file links, it’s very useful if you want to “add” a variety of document types, like .pdf, .doc, .rtf or .txt to your page.

image
File fields can easily be added to any ACF group. Use the ‘Add Field’ button and select ‘File’ in the ‘Field Type’ dropdown.

ACF File field has 3 options in the Return Type setting: File Array, File URL, File ID. This setting doesn’t affect the field’s look for admin editors but controls format of the value which you get back in code, when you request the field value from the Database.

Therefore I would suggest that you use the ‘File ID’ option, it’s the best choice for performance and allows you to get any extra data about the selected attachment, like File name or Upload Date. Steer clear of the ‘File URL’ option, unless you need this option for some specific goal, as it doesn’t allow to get any extra data about the attachment.

image
Admins and Editors can choose any file from the Media Library or upload a new one.

image
When you’ve assigned the file you can hover your cursor on the file and click the ‘pencil’ icon to edit file details (e.g. title) or click on the ‘X’ icon to remove the file.

ACF File. Behind the scenes

As we mentioned the File field works with the Media Library and allows you to add all sorts of attachments to pages, but you need to know that when you “add” a file it actually means “attach”, not copy. The field is just the middleman between a page and the Media Library and associates the ID from the file you’ve chosen to Post Meta of the current page, without creating duplicates or physical copies of the file.

Even in the case, when you are uploading a new attachment through the field upload dialogue box, the file will be uploaded to the Media Library like an ordinary attachment with the file field only storing the Attachment ID. In this way you can “attach” one file to many pages and it won’t create copies.

You would still need to give clear names for your attachments and you should really try and avoid uploading the same file multiple times, because the Media Library doesn’t know if the attachment being uploaded is a completely new one or if it already exists. So if you’re unsure then do a quick search in the Media Library before uploading, otherwise you’ll have a lot of headaches over time with multiple copies of the same thing.

Furthermore the Return Format setting also doesn’t affect the stored value, it’s always an Attachment ID. In case you’ve not selected the ‘File ID’ Return Format, then every time you request the field the ACF plugin will do extra work to convert the saved Attachment ID to another format, that’s why it’s better for performance to use the native “File ID” option.

Display ACF File field with PHP code

In most cases, we would need to turn the File field into a link to show to users, so when they try and download the attachment or open it in a new browser tab it’s easy for them. To do this you would need to get the file URL (and probably the name too) and then create the HTML for the link.

The code will be different depending on the selected Return Type. Below we provided examples.

  1. PHP code to display the File field with the “ID” Return Format:
<?php

// don't forget to replace 'file' with your field name
$fileID = get_field('file');
if ($fileID) {
   // $fileID is an ID (integer) of a Post with the Attachment type. 
   // we need to use the built-in WP functions to get necessary data
    $url = wp_get_attachment_url($fileID);
    $name = get_post($fileID)->post_title ?? '';
    // displays the file. Each %s in the string will be replaced with the related argument
    printf("<a href='%s' download='%s'>%s</a>", esc_attr($url), esc_attr($name), esc_html($name));
}
Enter fullscreen mode Exit fullscreen mode
  1. PHP code to display the File field with the “Array” Return Format:
<?php

// don't forget to replace 'file' with your field name
$fileData = get_field('file');
if ($fileData) {
    // displays the file. Each %s in the string will be replaced with the related argument
    printf("<a href='%s' download='%s'>%s</a>", 
     esc_attr($fileData['url']), esc_attr($fileData['filename']), esc_html($fileData['filename']));
}
Enter fullscreen mode Exit fullscreen mode
  1. PHP code to display the File field with the “URL” Return Format:
<?php

// don't forget to replace 'file' with your field name
$fileUrl = get_field('file');
if ($fileUrl) {
    // displays the file. Each %s in the string will be replaced with the related argument
    printf("<a href='%s' download='prices.pdf'>Prices.pdf</a>", esc_attr($fileUrl));
}
Enter fullscreen mode Exit fullscreen mode

We’ve used the download attribute (read more) to let a client’s browser know, that instead of opening this file must be downloaded. The value of the attribute will be used as the name of the downloading file. Remove the attribute if you want this file to be opened instead of downloaded.

With the “URL” Return Format we’ve to hardcode the file name. There is no way to use this code for different files or amend it without code editing. That’s why it’s better always to choose the “ID” Return Format.

You can find more information in the official ACF article.

Display ACF File field with shortcodes

Shortcodes are one of the most powerful and easy to use WordPress features out there. Shortcodes allow you to “call” PHP functions directly in your editor, like Gutenberg, this allows you to display dynamic content pieces.

To create a shortcode you’d need to write PHP code, but we’re not going to do that today, we’re going to use a free plugin called ACF Views that’ll do all the work for us, and will allow you to display any ACF field, using automatically generated shortcodes.

Below we’ll see how to display a link on the front-end of your website for any File field without writing any code.

If you want to follow along you need to; a) install the ACF Views plugin on your WordPress site and don’t forget to activate it. It’s an addon to ACF, so you’ll also need to b) install the free Advanced Custom Fields (ACF) plugin and active it.

Step 1. Creating a View

After you’ve activated the ACF Views plugin you’ll see a new item in your admin menu, called “ACF Views”.

That item has a sub menu, with several items, but we’ll only need to use the one called ‘ACF Views’.

image
Your list will have the same look but without any View items.

Click on the “Add New” button to create a View.

Note: The term “View” is the name given for the special Post Type the plugin provides. Every View is a list of ACF fields to display, so you may have many different Views to display different fields (or sets of fields) for different posts/pages.

Then give your View a name, you can use anything that describes the View, this name will only be displayed in the list of Views, making it easier to find. I’ve called my View “Page catalog”.

image

Now you’ll need to assign a new field to your View. Click the ‘Add Field’ button and select your ‘Group’ from the dropdown, in my case the group is called “Page fields”, continue to select the target field from the list, I’ve selected “Catalog (file)”. Notice that the field type is shown in brackets after the file name, that’s so you can easily identify the type of field. You should also see the type as “file”. Define a “Link Label” for our future link or leave it empty, if you want the plugin to pick it up from the selected attachment.

Overall every View can have an unlimited amount of ACF fields, for our case we’ll use only one.

Click on the ‘Publish’ button to save and publish your View _. As soon it’s published you’ll notice that Shortcodes were generated in a block on the right side of your _View edit screen. Every View has its own shortcode with a unique ID (the shortcode structure is the same for all Views, but arguments are unique).

[acf_views view-id="xxxx" name="x"]
Enter fullscreen mode Exit fullscreen mode

Now we need to copy the shortcode, for this goal click on the ‘Copy to clipboard’ button on the first shortcode.

Step 2. Paste the shortcode in place

Now that we’ve prepared everything we are ready to display the File field.

Visit your target page, this will be where you have the file field. Remember to check that there is an attachment in your File field, paste the shortcode anywhere you’d like in the page content.

To paste the shortcode with the Gutenberg editor, just click on the plus button in the top bar and choose the “Shortcode” block from the list, then paste your shortcode in the block and click the ‘Update’ button to save your post/page.

image
Gutenberg block with an ACF Views shortcode.

Visit the page to see the result, and if you’ve done everything correctly then you should see your selected file displayed in the content as a link, with your defined label (or with the File Name of the attached File in case you’ve left it empty).

image
ACF File field displayed as a link with a shortcode on a page.

If you can’t see your link, then go back and edit the page. Make sure you’ve attached a File to the ACF file field because if the field is empty it’ll have nothing to display.

Final thoughts

We’ve taken a closer look at the ACF File field, how to use it and how to display it, we’ve talked about the important aspects that you need to remember when using this field type, and we’ve also gone through some reasons why coding the output takes extra time and most of all, we’ve shown how to quickly and easily display a File field (or any ACF field for that matter) using generated shortcodes, which requires no coding at all. The ACF Views plugin makes the task much easier, as it creates HTML markup automatically and also takes care of the Return Formats. Just select ACF fields and use the provided shortcode to display the fields — that’s it!

It’s useful to know that you can have multiple fields (even from different groups) in a single View, you can style the fields output using the CSS code field (see the View’s Advanced Tab), that CSS will only be printed on pages where you’re using the shortcode, so you don’t need to search for a place to put it.

Visit the ACF Views official website to get more information about the plugin, you can also find links to the plugin’s YouTube channel that has video tutorials and the plugin Documentation. Those resources will help you get familiar with the plugin faster.

Top comments (0)