Quickstart

Quickstart

Installation

Run the following command in the root of your project/theme/plugin:

composer require jorenrothman/acf-builder

Creating a Field Group

Create a new instance of the FieldGroup class and pass it a title.

<?php
 
use JorenRothman\ACFBuilder\FieldGroup;
 
$fieldGroup = new FieldGroup('My Field Group');

Adding Fields

Fields can be created with new or with the static ::make() factory, which allows cleaner chaining.

<?php
 
use JorenRothman\ACFBuilder\FieldGroup;
use JorenRothman\ACFBuilder\Fields\Basic\Text;
 
$fieldGroup = new FieldGroup('My Field Group');
 
$fieldGroup->addField(
    Text::make('My Text Field')->setRequired(true)
);

Field Group Locations

By default, a field group has no location rules. Use FieldGroupLocations to control where it appears. Chain and() to add rules within the same group, and or() to add an alternative group.

<?php
 
use JorenRothman\ACFBuilder\FieldGroup;
use JorenRothman\ACFBuilder\Fields\Basic\Text;
use JorenRothman\ACFBuilder\FieldGroupLocations;
 
$fieldGroup = new FieldGroup('My Field Group');
 
$fieldGroup->addField(
    Text::make('My Text Field')
);
 
$locations = new FieldGroupLocations();
$locations->and('post_type', '==', 'page');
 
$fieldGroup->setLocations($locations);

Register Field Group

Once you've created a field group, register it with ACF using the register() method. You can optionally pass a FieldGroupLocations instance directly to register().

<?php
 
use JorenRothman\ACFBuilder\FieldGroup;
use JorenRothman\ACFBuilder\Fields\Basic\Text;
use JorenRothman\ACFBuilder\FieldGroupLocations;
 
$fieldGroup = new FieldGroup('My Field Group');
 
$fieldGroup->addField(
    Text::make('My Text Field')
);
 
$locations = new FieldGroupLocations();
$locations->and('post_type', '==', 'page');
 
$fieldGroup->register($locations);

Go to the WordPress admin and you should see your field group.

Querying Fields

To query the field you can use the standard get_field function.

The name is automatically generated using the field group name + field name.

For example, if the field group name is My Field Group and the field name is My Text Field, the field name will be my_field_group_my_text_field.

<?php
 
$fieldValue = get_field('my_field_group_my_text_field');

A field name is created by converting the field group name and field name to snake_case and concatenating them with an underscore.