The Advanced Custom Fields plugin is packed with loads of useful field types such as text, image and WYSIWYG. However, when working on a project, it may be necessary to create a new type of field to save & load unique data.
This guide will demonstrate how to create a new field type for the ACF plugin.
To make life easier, we put together a comprehensive template for creating an ACF field type, complete with an NPM script that get you up and running even faster.
ACF Example Field Type template on Github
Please download or clone the ACF Example Field Type repository. Alternatively, you can click the green “Use this template” button to create a new repository based on this template.
Once you’ve downloaded the template, follow the steps in the README to get started on your custom field type.
All logic for your field’s appearance and functionality is defined in the
acf-FIELD-NAME/class-PREFIX-acf-field-FIELD-NAME.php file. This class extends the
acf_field class, which is packed full of powerful functions which allow you to customize how data is saved and displayed! Each function is documented with internal comments, so it is best to open up the file and read it over top to bottom.
Here is a quick overview of the functions:
|Initialize function which sets the field’s data such as name, label, category and defaults
|Create extra settings for your field. These are visible when editing a field
|Create the HTML interface for your field
|Add hidden inline HTML
|This filter is applied to the $value after it is loaded from the db
|This filter is applied to the $value before it is saved in the db
|This filter is applied to the $value before being returned to template API
|This filter is used to perform validation on the value prior to saving
|This action is fired after a value has been deleted from the db
The above are only some of the functions available in the acf_field class. Please read over the extended comments found above each function to learn more.
Some field types may output potentially unsafe HTML directly, such as iframes or script tags.
Starting from ACF 6.2.5, where these would automatically be removed when using the ACF shortcode or
the_field(), ACF supports field types escaping their own HTML when requested. This is done by a second parameter being passed into the
format_value method, if this value is true, we require a HTML safe version of the output.
In this instance, your field type should ensure there is no way for malicious HTML to be rendered on the front-end by a malicious user modifying the raw value in the database. For example, the core WYSIWYG field handles this by running
acf_esc_html on the value before running
the_content filter to handle any embeds in the field.
Once your field type is ready to handle its own HTML, you can mark the field as compatible by adding
’escaping_html’ => true to the new
supports class property:
$this->supports = array(
'escaping_html' => true,