WPLake > Learning Hub > ACF File Field
  • Deutsch
  • Español
  • Français
  • Italiano

ACF File Field

Explore supported file types and extensions, along with flexible return formats of the ACF File field, and simplify displaying with smart templates.

Key Points at a Glance

  1. ACF File Field Basics: The ACF File field allows attachment of various file types from the Media Library to pages, offering flexibility beyond images.
  2. File Extension Support: Unlike the Image field, the File field supports a wide range of file extensions, including common document types like .pdf and .doc.
  3. Return Formats: The File field offers three return format options: File Array, File URL, and File ID, each influencing the format of the retrieved data.
  4. Internal Functionality: Files attached via the File field are not duplicated but linked to the Media Library, allowing attachment to multiple pages without duplication.
  5. Displaying File Fields with PHP Code: PHP code examples are provided for displaying File fields based on different return formats, offering control over link creation.
  6. Smart Templates with Advanced Views: The Advanced Views framework introduces smart templates built on the Twig engine, streamlining content display without manual PHP coding.

Table of Contents

About the File field

Advanced Custom Fields is one of the best plugins for managing meta fields and Custom Post Types (CPTs). The File field is one of the ACF field types, and it enables you to attach files from the Media Library to any page.

In contrast to the Image field, which exclusively permits the selection of image files (e.g., .png, .jpg, .gif), the File field offers the flexibility to choose files with various extensions from your Media Library, including common document types like .pdf and .doc.

However, unlike the Image field, the File field doesn't provide a preview of the selected file. Instead, it displays the File Name and File Size. Typically, developers utilize this field type to create download or "open" file links.

The field supports a wide range of file extensions. You can refer to the related WordPress.org page for a comprehensive list of allowed extensions for various file types.

You can effortlessly add File fields to any ACF group by using the 'Add Field' button and selecting 'File' from the 'Field Type' dropdown.

Return formats

The ACF File field offers three options in the Return Type setting: File Array, File URL, and File ID. This setting doesn't impact the field's appearance for admin editors but determines the format of the value you receive in code when requesting the field value from the database.

Therefore, it's advisable to use the 'File ID' option, as it offers the best performance and allows you to access additional data about the selected attachment, such as the File name or Upload Date. It's recommended to avoid the 'File URL' option unless you have a specific need for it, as it doesn't provide access to extra data about the attachment.

Admins and Editors have the flexibility to select any file from the Media Library or upload a new one.
Once you have assigned the file, you can hover your cursor over it and click the 'pencil' icon to edit file details (e.g., title), or click the 'X' icon to remove the file.

Behind the ACF scenes

As previously mentioned, the File field operates in conjunction with the Media Library and allows you to attach various types of files to pages. It's important to understand that when you "add" a file, it actually means "attach." It doesn't create duplicates or physical copies of the file. Instead, the field serves as an intermediary between a page and the Media Library, associating the chosen file's ID with the Post Meta of the current page.

Even when you upload a new attachment through the field's upload dialogue box, the file will be uploaded to the Media Library as a regular attachment, with the file field storing only the Attachment ID. This approach allows you to "attach" one file to multiple pages without generating copies.

To maintain clarity, it's advisable to provide clear names for your attachments and avoid uploading the same file multiple times. The Media Library doesn't distinguish between a completely new attachment and an existing one, so conducting a quick search in the Media Library before uploading is a good practice. Otherwise, you may encounter issues with multiple copies of the same file over time.

Furthermore, the Return Format setting does not affect the stored value, which always remains an Attachment ID. If you haven't selected the 'File ID' Return Format, the ACF plugin will perform additional work to convert the stored Attachment ID into another format whenever you request the field. Hence, for optimal performance, it's recommended to use the native "File ID" option.

Display File field using Smart templates

Let's get familiar with the Advanced Views framework.

Advanced Views introduces smart templates for effortless content display. It comes with built-in post queries and automated template generation, enabling rapid development while maintaining flexibility.

Let's first clarify what we mean by 'templates' in the context of this plugin: Advanced Views templates are built on the Twig engine. You might be thinking, 'Not bad, but it still requires fetching fields via PHP and writing markup from scratch, not to mention reading Twig documentation'.

Here's where the plugin shines: "Smart templates". This means we don't have to fetch fields or create markup manually from scratch. The plugin provides a solid foundation that covers most use cases. If we require something specific, we can easily customize it. Isn't that nice?

Basics

Now, let's take a basic look at how it works.

The plugin introduces two new Custom Post Types (CPTs): ACF View and ACF Card.

  • View for post data and Advanced Custom Fields
    We create a View and assign one or more post fields, the plugin then generates a shortcode that we'll use to display the field values to users. We can style the output with the CSS field included in every View.
  • Card for post selections
    We create a Card and assign posts (or CPT items), choose a View (that will be used to display each item) and the plugin generates a shortcode that we'll use to display the set of posts. The list of posts can be assigned manually or dynamically with filters.

The plugin offers us the convenience of working with familiar WordPress CPTs while taking care of querying and automatically generating Twig markup templates. You can find more information about the plugin's benefits here.

To follow along; install the Advanced Views framework on your WordPress site and remember to activate it. You'll also need the ACF (free) plugin installed and active. Then continue to the next steps below.

Step 1. Creating a View

When you activate the Advanced Views framework, you'll notice a new item in your admin menu titled "Advanced Views."

Within the submenu, you'll find several items, but the one you'll need to use is called 'Advanced Views'.

ACF Views provides list management via the familiar interface.
Your list will have the same appearance, but it won't contain any View items.

Visit the Advanced Views tab and click the 'Add New' button to create a View.

Provide a name for your View. It can be anything that describes the View, as this name will be displayed in the list of Views, making it easier to identify. For example, we've named our View "Page catalog".

ACF Views allow to assign multiple fields within your View.

Assigning fields

Now, you'll need to assign a new field to your View. To do this, follow these steps:

  1. Click the 'Add Field' button.
  2. Select your 'Group' from the dropdown. In my case, the group is named "Page fields."
  3. Next, select the target field from the list. I've chosen "Catalog (file)."

Note: The field type is indicated in brackets after the field name, making it easy to identify the type of any field in the dropdown.

You should also notice that the type is listed as "file." Optionally, you can define a "Link Label" for your future link, or you can leave it empty if you want the plugin to use the label from the selected attachment.

Every View can accommodate an unlimited number of ACF fields, but for our example, we're using only one.

Finally, click on the 'Publish' button to save and publish your View. Once published, you'll see that Shortcodes have been generated in a block on the right side of your View edit screen. Each View has its unique shortcode with a unique ID.

[acf_views view-id="xxxx" name="x"]

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 completed all the preparations, we're ready to display the File field.

Here are the steps to follow:

  1. Visit your target page, where you have the File field.
  2. Ensure that there is an attachment in your File field.
  3. Paste the shortcode anywhere you'd like within the page content.

If you're using the Gutenberg editor, you can paste the shortcode by clicking on the plus button in the top bar and selecting the "Shortcode" block from the list. Then, paste your shortcode into the block and click the 'Update' button to save your post/page.

Gutenberg block containing an Advanced Views shortcode.

Visit the page to view the result. If you've followed the steps correctly, you should see your selected file displayed in the content as a link, along with your defined label or the File Name of the attached File if you left it empty.

The ACF File field is displayed as a link using a shortcode on the page.

If you cannot see your link, please follow these steps:

  1. Go back and edit the page.
  2. Ensure that you have attached a File to the ACF File field because if the field is empty, it won't display anything.

Display File field using PHP code

In most cases, you'll want to transform the File field into a link to make it user-friendly for downloading or opening in a new browser tab. To achieve this, you'll need to retrieve the file URL (and possibly the file name) and then create the HTML for the link.

The code will vary depending on the selected Return Type. Below, we've provided examples of the get_field function usage for your reference.

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));
}

2. 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']));
}

3. 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));
}

We've used the download attribute (read more) to inform the user's browser that instead of opening the file, it should be downloaded. The value of the attribute is used as the name of the downloaded file. You can remove the attribute if you want the file to be opened rather than downloaded.

When using the "URL" Return Format, you'll need to manually hardcode the file name. This means you have to specify the file name in the code, and it cannot be easily adapted for different files without code editing. That's why it's generally recommended to choose the "ID" Return Format for more flexibility.

For additional information, you can refer to the video below and read the official ACF article.

ACF File field with code, video cover

Final thoughts

You've now gained a deeper understanding of the ACF File field and how to utilize and display it. We've highlighted key points to remember when working with this field type.

It's worth noting that you can include multiple fields from different groups within a single View, and you can customize the output of these fields using the CSS code field (located in the View's Advanced Tab). The plugin will apply this CSS only on pages where you've used the shortcode, eliminating the need to search for a suitable place to add it.

For more information about the Advanced Views framework, visit the official website. You can also access the plugin's YouTube channel, which features video tutorials, and explore the plugin's documentation. These resources will help you become more proficient with the plugin.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

FAQ mode

/

Learning mode

  1. What is the ACF File field, and how does it differ from the Image field?

    The ACF File field allows you to attach various file types from the Media Library to pages. Unlike the Image field, it supports a wide range of file extensions beyond images.

  2. What return format options are available for the ACF File field?

    The ACF File field offers three return format options: File Array, File URL, and File ID, each influencing the format of the retrieved data when accessing the field value from the database.

  3. How does the ACF File field function internally with attachments?

    The File field operates by linking files to the Media Library rather than duplicating them, allowing for attachment to multiple pages without generating copies.

  4. What are some best practices for working with the ACF File field?

    It's advisable to provide clear names for attachments, avoid uploading duplicates, and select the appropriate return format based on specific needs for optimal performance.

  5. What is Advanced Views, and how does it enhance content display?

    Advanced Views is a plugin that introduces smart templates built on the Twig engine, simplifying content display without manual PHP coding.

Related articles

Content links (15)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it