Skip to content

ACF custom blocks

Creating Custom ACF Blocks

In Advanced Custom Fields (ACF), creating custom fields is a powerful way to adapt your website to specific project needs. We often create ACF blocks for various common tasks such as background color selection, color options, or custom spacing to give our content editors more control over the appearance and layout of their pages without needing to touch code.

In this section, we’ll explain how to create a basic custom ACF field, using a background color selection as an example.

Note: please remember we tend to use some of the blocks from project to project: custom spacing, background color, color options, etc.

1. Custom ACF Field Example: Background Color Selector

To create a custom ACF block, we’ll break down the code into several components. Here’s the basic process for creating a new field like background color:

Step 1: Defining the Field Type

We start by defining the custom ACF field type class. This is the core logic for how the field behaves in the ACF interface.

class PREFIX_acf_field_backgroundcolor extends \acf_field
{
public $show_in_rest = true; // Allows the field to be visible in the REST API.
private $env; // Store environment variables like plugin or theme context.
public function __construct()
{
$this->name = 'backgroundcolor'; // The field name used in PHP and JS code.
$this->label = __('Background Color', 'TEXTDOMAIN'); // The label shown in the ACF field settings.
$this->category = 'basic'; // The category where the field appears in the ACF field type picker.
$this->defaults = array('font_size' => 14); // Default settings for the field.
$this->l10n = array('error' => __('Error! Please enter a higher value', 'TEXTDOMAIN')); // Localization strings.
$this->env = array(
'url' => site_url(str_replace(ABSPATH, '', __DIR__)), // URL to the field’s directory.
'version' => '1.0', // Version number of the theme or plugin.
);
parent::__construct();
}
}

In this part:

  • The name is the identifier of the field (used in the PHP/JS code).
  • The label is what will be displayed in the admin interface.
  • The category groups the field within the ACF field types.

Step 2: Rendering Field Settings

Next, we define what settings will appear when the user configures the field in the ACF admin interface.

public function render_field_settings($field)
{
// Here you can add additional field settings.
// For example, you could add font size or custom options for this field type.
}

In this function, you can render additional settings that the user will interact with when configuring the field. For example, you could allow users to choose which colors are available in the dropdown.

Step 3: Rendering the Field on the Edit Screen

Now, we define how the field will appear on the edit screen when users are creating or editing a post.

public function render_field($field)
{
?>
<div class="dropdown-color js--background-color">
<div class="selected">
<a href="#"><span>Please select</span></a>
</div>
<div class="options js--select-background-color">
<ul>
<li value="primary"><a href="#" class="c--color-bg-a" data-value="f--background-a">
<div></div>White
</a></li>
<li><a href="#" data-value="f--background-b" class="c--color-bg-a c--color-bg--grey">
<div></div>Grey
</a></li>
</ul>
</div>
</div>
<input type="hidden" class="setting-font-size js--background-color" name="<?php echo esc_attr($field['name']) ?>"
value="<?php echo esc_attr($field['value']) ?>" />
<?php
}

In this part, we create a dropdown color selector for the user to pick a background color. The selected color will be stored as the field’s value.

Step 4: Enqueueing Scripts and Styles

To make the field interactive (with dropdowns, color selection, etc.), we need to enqueue custom JavaScript and CSS.

public function input_admin_enqueue_scripts()
{
$url = trailingslashit($this->env['url']);
$version = date("F j, Y, g:i a");
wp_register_script(
'PREFIX-backgroundcolor',
"{$url}assets/js/background-color.js",
array('acf-input'),
$version
);
wp_register_style(
'PREFIX-backgroundcolor',
"{$url}assets/css/background-color.css",
array('acf-input'),
$version
);
wp_enqueue_script('PREFIX-backgroundcolor');
wp_enqueue_style('PREFIX-backgroundcolor');
}

Here, we link to the custom JS and CSS files that make the dropdown color selector functional and styled. The script will handle the interactivity of the field (e.g., showing/hiding the dropdown when clicked).

Step 5: Registering the Field

Finally, we register the new field type with ACF so that it can be used in the WordPress admin.

add_action('init', 'PREFIX_include_acf_field_backgroundcolor');
function PREFIX_include_acf_field_backgroundcolor()
{
if (!function_exists('acf_register_field_type')) {
return;
}
require_once __DIR__ . '/class-PREFIX-acf-field-backgroundcolor.php';
acf_register_field_type('PREFIX_acf_field_backgroundcolor');
}

This function tells WordPress to include our custom field and register it with ACF, making it available for use in the admin interface.

2. Custom JavaScript for the Color Selector

Here’s the accompanying JavaScript that controls the dropdown behavior and the color selection:

(function ($) {
function getColorName(className) {
switch (className) {
case "f--background-a":
return "White";
case "f--background-b":
return "Grey";
default:
return "Select a background color";
}
}
function initialize_field($field) {
$.each($($field.find(".js--background-color")), function () {
var selector = $(this).find(".options ul");
var selectorSpan = $(this).find(".selected a span");
$(this).find(".selected a").click(function () {
selector.toggle();
});
$(this).find("ul li a").click(function () {
$field.find("input").val($(this).attr("data-value"));
selectorSpan.html(`<div class="${$(this).attr("data-value")}">` + getColorName($field.find("input").val()) + "</div>");
selector.hide();
});
if ($field.find("input").val()) {
selectorSpan.html(`<div class="${$field.find("input").val()}">` + getColorName($field.find("input").val()) + "</div>");
}
});
}
if (typeof acf.add_action !== "undefined") {
acf.add_action("ready_field/type=backgroundcolor", initialize_field);
acf.add_action("append_field/type=backgroundcolor", initialize_field);
}
})(jQuery);

This script manages the interactivity of the color selector, showing and hiding the color options, and setting the selected color as the field’s value.

3. Custom CSS

Custom CSS defines the visual styles for the background color selector, including the colors for the options. This CSS ensures the field is displayed correctly in the ACF editor. Here’s an example of the custom CSS:

/* Custom styles for the background color field */
.js--background-color .selected a {
display: flex;
align-items: center;
}
.c--color-bg-a div, .c--color-bg-b div {
width: 20px;
height: 20px;
margin-right: 10px;
}
.c--color-bg-a {
background-color: white;
}
.c--color-bg-b {
background-color: grey;
}
.options ul {
display: none;
list-style-type: none;
padding: 0;
}
.options ul li {
padding: 10px;
cursor: pointer;
}

This CSS handles the color selection interface, ensuring it looks clean and functional in the ACF editor.