Регистрация полей через PHP

Advanced Custom Fields (ACF)

В этой статье мы рассмотрим, как регистрировать поля и группы полей в PHP, например в файле functions.php, а не через визуальный редактор ACF.

Плюсы создание полей напрямую в PHP полезно:

  • позволяет разработчикам избежать рассинхронности данных при работе в разных средах dev/staging/prod.
  • уменьшает количество обращений к базе данных.

Для поддержки одинаковых данныp (синхронности) в разных средах, также можно использовать acf-json. Его недостаток в том, что данные все также хранятся в БД и их нужно обновлять вручную при обновлении json файла.

Заметки

  • ACF может сгенерировать готовый PHP код для создания полей через PHP. Для этого перейдите на страницу Инструменты (Tools) там есть Импорт / Экспорт:

  • Ключ каждой группы и поля должны быть уникальными. Ключ это идентификатор для ACF для поиска, сохранения и загрузки данных. Если есть одинаковые ключи у группы или поля, то приоритет будет иметь более поздний ключ.

  • Группы и поля, созданные через код, не будут видны в админке.

Функции

Здесь приведен список функций, которые будут использоваться в приведенных ниже примерах. Вы можете найти эти и другие функции в файле /acf/includes/local-fields.php.

Функция Описание
acf_add_local_field_group( $field_group ) acf_add_local_field_group
acf_add_local_field( $field, $prepared ) acf_add_local_field
acf_get_local_field( $key ) acf_get_local_field
acf_remove_local_field( $key ) acf_remove_local_field

Примеры

Функции создания груп и полей необязательно вызывать на хуке acf/init. Однако это рекомендуемый способ который был добавлен в ACF v5.2.7. Такая регистрация, не вызовет PHP ошибок, если плагин деактивировать.

Минимальный код

В этом примере показано, как добавить группу и поля дня неё.

Каждое поле содержит множество настроек, которые могут быть удалены для минимизации кода. Недостающие поля будут заполнены значениями по умолчанию.

add_action( 'acf/init', 'my_acf_init' );

function my_acf_init() {

	acf_add_local_field_group( [
		'key'      => 'group_1',
		'title'    => 'My Group',
		'fields'   => [
			[
				'key'   => 'field_1',
				'label' => 'Sub Title',
				'name'  => 'sub_title',
				'type'  => 'text',
			],
		],
		'location' => [
			[
				[
					'param'    => 'post_type',
					'operator' => '==',
					'value'    => 'post',
				],
			],
		],
	] );
}

Полный код

add_action( 'acf/init', 'my_acf_init' );

function my_acf_init() {

	acf_add_local_field_group( [
		'key'    => 'group_1',
		'title'  => 'My Group',
		'fields' => [
			[
				'key'               => 'field_1',
				'label'             => 'Sub Title',
				'name'              => 'sub_title',
				'type'              => 'text',
				'prefix'            => '',
				'instructions'      => '',
				'required'          => 0,
				'conditional_logic' => 0,
				'wrapper'           => [
					'width' => '',
					'class' => '',
					'id'    => '',
				],
				'default_value'     => '',
				'placeholder'       => '',
				'prepend'           => '',
				'append'            => '',
				'maxlength'         => '',
				'readonly'          => 0,
				'disabled'          => 0,
			],
		],
		'location' => [
			[
				[
					'param'    => 'post_type',
					'operator' => '==',
					'value'    => 'post',
				],
			],
		],
		'menu_order'            => 0,
		'position'              => 'normal',
		'style'                 => 'default',
		'label_placement'       => 'top',
		'instruction_placement' => 'label',
		'hide_on_screen'        => '',
	] );
}

Раздельное создание групп и полей

Можно добавить группу и поле по отдельности. Это позволяет определить поле как переменную и добавить его в несколько групп полей.

Обратите внимание, что в этом случае для field нужно указать параметр parent, который совпадает с key группы полей или другого родительского поля (повторитель / гибкое содержимое). Когда поля регистрируются вместе с группой ACF устанавливает parent автоматически.

add_action( 'acf/init', 'my_acf_init' );

function my_acf_init() {

	acf_add_local_field_group( [
		'key'      => 'group_1',
		'title'    => 'My Group',
		'fields'   => [],
		'location' => [
			[
				[
					'param'    => 'post_type',
					'operator' => '==',
					'value'    => 'post',
				],
			],
		],
	] );

	acf_add_local_field( [
		'key'    => 'field_1',
		'label'  => 'Sub Title',
		'name'   => 'sub_title',
		'type'   => 'text',
		'parent' => 'group_1',
	] );
}

Group (аргументы)

Ниже приведен список доступных настроек для группы. Полный актуальный список параметров можно просмотреть при создании группы и поля в админке.

$group = [
	'key'      => 'group_1',
	'title'    => 'My Group',
	'fields'   => [],
	'location' => [
		[
			[
				'param'    => 'post_type',
				'operator' => '==',
				'value'    => 'post',
			],
		],
	],
	'menu_order'      => 0,
	'position'        => 'normal',
	'style'           => 'default',
	'label_placement' => 'top',
	'hide_on_screen'  => '',
	'instruction_placement' => 'label',
];
key(string)
Unique identifier for field group. Must begin with group_.
По умолчанию: 'group_' . acf_slugify( $field_group['title'], '_' )
title(string)
Visible in metabox handle
По умолчанию: ''
fields(array)
An array of fields
По умолчанию: []
location(array)

Массив, содержащий "группы правил", где каждая "группа правил" - это массив, содержащий "правила". Группы между собой обрабатываются как "OR", а правила внутри групп как "AND".

'location' => [
	// rule group (considered OR)
	[
		// rule (considered AND)
		[
			'param'    => 'post_type',
			'operator' => '==',
			'value'    => 'post',
		],
		...
	],
	...
],

Значение param это свойство name класса ACF_Location_*{}. См: acf_register_location_type().

attachment
comment
current_user
current_user_role
nav_menu
nav_menu_item
page
page_type
page_parent
page_template
post
post_type
post_category
post_format
post_status
post_taxonomy
post_template
taxonomy
user_form
user_role
widget
block
options_page

Значение operator может быть:

==
!=

Значение value зависит от того что указано в param. См. метод соответствующего класса ACF_Location_*{}.

page_type         > front_page | posts_page | top_level | parent | child
page              > 123 | ...
post              > 123 | ...
post_type         > post | page | ...
post_category     > category:aciform | category:sub-cat | ...
post_taxonomy     > category:aciform | post_format:post-aside | post_tag:alignment-2 | ...

attachment        > image | image/jpeg | audio | video ...
comment           > post | page | attachment | all
current_user      > logged_in | viewing_front | viewing_back
nav_menu_item     > location/primary | 178 | ...
current_user_role > author | administrator | ...

...

По умолчанию: []

menu_order(int)
Field groups are shown in order from lowest to highest. Defaults to 0
По умолчанию: 0
position(string)
Determines the position on the edit screen. Defaults to normal. Choices of 'acf_after_title', 'normal' or 'side'
По умолчанию: 'normal'
style(string)
Determines the metabox style (theme). Defaults to default. Choices of default or seamless (requires label_placement=left).
По умолчанию: 'default'
label_placement(string)
Determines where field labels are places in relation to fields. Defaults to top. Choices of top (Above fields) or left (Beside fields).
По умолчанию: 'top'
instruction_placement(string)
Determines where field instructions are places in relation to fields. Defaults to 'label'. Choices of label (Below labels) or field (Below fields).
По умолчанию: 'label'
hide_on_screen(array)

Массив элементов для скрытия на экране. Указанный тут метабокс просто скрывается через css. См. acf_get_field_group_style()

Возможные значения массива:

array(
	'permalink',
	'the_content',
	'excerpt',
	'custom_fields',
	'discussion',
	'comments',
	'slug',
	'author',
	'format',
	'page_attributes',
	'featured_image',
	'revisions',
	'categories',
	'tags',
	'send-trackbacks',
);

По умолчанию: [] ничего не скрывать

active(bool)
Активная группа или нет. Неактивные группы будут исключены из списка групп.
По умолчанию: true
description(string)
Shown in field group list.
По умолчанию: ''

Fields (аргументы)

Все классы полей из ядра смотрите по этой ссылке.

Общие параметры

Класс: acf_field{}

Ниже приведен список доступных общих настроек для поля. В дополнение к этим общим настройкам для каждого поля предусмотрены настройки, специфичные для конкретного типа поля, которые перечислены ниже.

$field = [
	'key'               => 'field_1',
	'label'             => 'Sub Title',
	'name'              => 'sub_title',
	'type'              => 'text',
	'instructions'      => '',
	'required'          => 0,
	'conditional_logic' => 0,
	'wrapper'           => [
		'width' => '',
		'class' => '',
		'id'    => '',
	],
	'default_value'     => '',
];
key(string) (required)
Unique identifier for the field. Must begin with 'field_'.
label(string) (required)
Visible when editing the field value.
name(string) (required)
Used to save and load data. Single word, no spaces. Underscores and dashes allowed.
type(string) (required)
Type of field (text, textarea, image, etc).
instructions(string)
Instructions for authors. Shown when submitting data.
По умолчанию: ''
required(int)
Whether or not the field value is required.
По умолчанию: 0
wrapper(array)

Массив дополнительных атрибутов для поля отображаемого в админке.

Пример: установим ширину select поля:

[
	'key'     => 'target',
	'name'    => 'target',
	'label'   => 'Target',
	'type'    => 'select',
	'choices' => [
		'_self'  => '_self',
		'_blank' => '_blank',
	],
	'wrapper' => [
		'width' => 15,
		'class' => 'some-css-class',
		'id'    => 'some-css-id',
	],
],

По умолчанию: []

default_value(mixed)
A default value used by ACF if no value has yet been saved.
По умолчанию: null
aria-label(string)
_______
conditional_logic(mixed)

Условия для того чтобы скрыть или показать текущиее поле, основываясь на значениях других полей.

Чтобы построить сложную логику, проще собрать поля в ACF UI и посмотреть как должно выглядеть поле conditional_logic через экспорт.

Пример: показывать поле popup_id только если is_active=true:

[
	'key'  => 'consent_is_active',
	'name' => 'is_active',
	'type' => 'true_false',
	//...
],
[
	'key'  => 'consent_popup_id',
	'name' => 'popup_id',
	//...
	'conditional_logic' =>
		[
			[
				[
					'field'    => 'consent_is_active',
					'operator' => '==',
					'value'    => '1',
				],
			],
		],
],

Пример: AND (будет показано если все поля соответствуют условию) и OR (будет показано если хотябы одно из полей соответствует условию) комбинаций:

// AND
[
	//...
	'conditional_logic' => [
		[
			[
				'field'    => 'consent_include_pages',
				'operator' => '==empty',
			],
			[
				'field'    => 'consent_is_active',
				'operator' => '==',
				'value'    => '1',
			],
		],
	],
],
// OR
[
	//...
	'conditional_logic' => [
		[
			[
				'field'    => 'consent_include_pages',
				'operator' => '==empty',
			],
		],
		[
			[
				'field'    => 'consent_is_active',
				'operator' => '==',
				'value'    => '1',
			],
		]
	],
],

По умолчанию: 0

separator

See: acf_field_separator{}.
Category: layout.

$separator_field = [
	'type'      => 'separator',
];

message

See: acf_field_message{}.
Cat: layout.

$message_field = [
	'type'      => 'message',
	'key'       => 'field_somekey',
	'label'     => 'Notes Title',
	'message'   => 'Note content',
	'new_lines' => '',              // br|wpautop|0. Default: wpautop
	'esc_html'  => 0,               // 1|0. Default 0. Use or not esc_html() for the content.
];

text, email, password

$text_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

	/* (string) Appears before the input. Defaults to '' */
	'prepend' => '',

	/* (string) Appears after the input. Defaults to '' */
	'append' => '',

	/* (string) Restricts the character limit. Defaults to '' */
	'maxlength' => '',

	/* (bool) Makes the input readonly. Defaults to 0 */
	'readonly' => 0,

	/* (bool) Makes the input disabled. Defaults to 0 */
	'disabled' => 0,

);

textarea

$textarea_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

	/* (string) Restricts the character limit. Defaults to '' */
	'maxlength' => '',

	/* (int) Restricts the number of rows and height. Defaults to '' */
	'rows' => '',

	/* (new_lines) Decides how to render new lines. Detauls to 'wpautop'.
	Choices of 'wpautop' (Automatically add paragraphs), 'br' (Automatically add <br>) or '' (No Formatting) */
	'new_lines' => '',

	/* (bool) Makes the input readonly. Defaults to 0 */
	'readonly' => 0,

	/* (bool) Makes the input disabled. Defaults to 0 */
	'disabled' => 0,

);

number

$number_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

	/* (string) Appears before the input. Defaults to '' */
	'prepend' => '',

	/* (string) Appears after the input. Defaults to '' */
	'append' => '',

	/* (int) Minimum number value. Defaults to '' */
	'min' => '',

	/* (int) Maximum number value. Defaults to '' */
	'max' => '',

	/* (int) Step size increments. Defaults to '' */
	'step' => '',

);

email

$email_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

	/* (string) Appears before the input. Defaults to '' */
	'prepend' => '',

	/* (string) Appears after the input. Defaults to '' */
	'append' => '',

);

url

$url_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

);

password

$password_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Appears within the input. Defaults to '' */
	'placeholder' => '',

	/* (string) Appears before the input. Defaults to '' */
	'prepend' => '',

	/* (string) Appears after the input. Defaults to '' */
	'append' => '',

);

color_picker

array(
	'type'           => 'color_picker',
	'default_value'  => '',
	'enable_opacity' => false,
	'return_format'  => 'string', // 'string'|'array'
);

wysiwyg

$wysiwyg_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Specify which tabs are available. Defaults to 'all'.
	Choices of 'all' (Visual & Text), 'visual' (Visual Only) or text (Text Only) */
	'tabs' => 'all',

	/* (string) Specify the editor's toolbar. Defaults to 'full'.
	Choices of 'full' (Full), 'basic' (Basic) or a custom toolbar
	https://www.advancedcustomfields.com/resources/customize-the-wysiwyg-toolbars/ */
	'toolbar' => 'full',

	/* (bool) Show the media upload button. Defaults to 1 */
	'media_upload' => 1,

);

oembed

$oembed_field = array(

	/* ... Insert generic settings here ... */

	/* (int) Specify the width of the oEmbed element. Can be overridden by CSS */
	'width' => '',

	/* (int) Specify the height of the oEmbed element. Can be overridden by CSS */
	'height' => '',

);

image

$image_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Specify the type of value returned by get_field(). Defaults to 'array'.
	Choices of 'array' (Image Array), 'url' (Image URL) or 'id' (Image ID) */
	'return_format' => 'array',

	/* (string) Specify the image size shown when editing. Defaults to 'thumbnail'. */
	'preview_size' => 'thumbnail',

	/* (string) Restrict the image library. Defaults to 'all'.
	Choices of 'all' (All Images) or 'uploadedTo' (Uploaded to post) */
	'library' => 'all',

	/* (int) Specify the minimum width in px required when uploading. Defaults to 0 */
	'min_width' => 0,

	/* (int) Specify the minimum height in px required when uploading. Defaults to 0 */
	'min_height' => 0,

	/* (int) Specify the minimum filesize in MB required when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'min_size' => 0,

	/* (int) Specify the maximum width in px allowed when uploading. Defaults to 0 */
	'max_width' => 0,

	/* (int) Specify the maximum height in px allowed when uploading. Defaults to 0 */
	'max_height' => 0,

	/* (int) Specify the maximum filesize in MB in px allowed when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'max_size' => 0,

	/* (string) Comma separated list of file type extensions allowed when uploading. Defaults to '' */
	'mime_types' => '',

);

file

$file_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Specify the type of value returned by get_field(). Defaults to 'array'.
	Choices of 'array' (File Array), 'url' (File URL) or 'id' (File ID) */
	'return_format' => 'array',

	/* (string) Specify the file size shown when editing. Defaults to 'thumbnail'. */
	'preview_size' => 'thumbnail',

	/* (string) Restrict the file library. Defaults to 'all'.
	Choices of 'all' (All Files) or 'uploadedTo' (Uploaded to post) */
	'library' => 'all',

	/* (int) Specify the minimum filesize in MB required when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'min_size' => 0,

	/* (int) Specify the maximum filesize in MB in px allowed when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'max_size' => 0,

	/* (string) Comma separated list of file type extensions allowed when uploading. Defaults to '' */
	'mime_types' => '',

);
$gallery_field = array(

	/* ... Insert generic settings here ... */

	/* (int) Specify the minimum attachments required to be selected. Defaults to 0 */
	'min' => 0,

	/* (int) Specify the maximum attachments allowed to be selected. Defaults to 0 */
	'max' => 0,

	/* (string) Specify the image size shown when editing. Defaults to 'thumbnail'. */
	'preview_size' => 'thumbnail',

	/* (string) Restrict the image library. Defaults to 'all'.
	Choices of 'all' (All Images) or 'uploadedTo' (Uploaded to post) */
	'library' => 'all',

	/* (int) Specify the minimum width in px required when uploading. Defaults to 0 */
	'min_width' => 0,

	/* (int) Specify the minimum height in px required when uploading. Defaults to 0 */
	'min_height' => 0,

	/* (int) Specify the minimum filesize in MB required when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'min_size' => 0,

	/* (int) Specify the maximum width in px allowed when uploading. Defaults to 0 */
	'max_width' => 0,

	/* (int) Specify the maximum height in px allowed when uploading. Defaults to 0 */
	'max_height' => 0,

	/* (int) Specify the maximum filesize in MB in px allowed when uploading. Defaults to 0
	The unit may also be included. eg. '256KB' */
	'max_size' => 0,

	/* (string) Comma separated list of file type extensions allowed when uploading. Defaults to '' */
	'mime_types' => '',

);

select

$select_field = array(

	/* ... Insert generic settings here ... */

	/* (array) Array of choices where the key ('red') is used as value and the value ('Red') is used as label */
	'choices' => array(
		'red'   => 'Red'
	),

	/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
	'allow_null' => 0,

	/* (bool) Allow mulitple choices to be selected. Defaults to 0 */
	'multiple' => 0,

	/* (bool) Use the select2 interfacte. Defaults to 0 */
	'ui' => 0,

	/* (bool) Load choices via AJAX. The ui setting must also be true for this to work. Defaults to 0 */
	'ajax' => 0,

	/* (string) Appears within the select2 input. Defaults to '' */
	'placeholder' => '',

);

checkbox

$checkbox_field = array(

	/* ... Insert generic settings here ... */

	/* (array) Array of choices where the key ('red') is used as value and the value ('Red') is used as label */
	'choices' => array(
		'red'   => 'Red'
	),

	/* (string) Specify the layout of the checkbox inputs. Defaults to 'vertical'.
	Choices of 'vertical' or 'horizontal' */
	'layout' => 'vertical',

	/* (bool) Whether to allow custom options to be added by the user. Default false. */
	'allow_custom' => false,

	/* (bool) Whether to allow custom options to be saved to the field choices. Default false. */
	'save_custom' => false,

	/* (bool) Adds a "Toggle all" checkbox to the list. Default false. */
	'toggle' => false,

	/* (string) Specify how the value is formatted when loaded. Default 'value'.
	Choices of 'value', 'label' or 'array' */
	'return_format' => 'value',

);

radio

$radio_field = array(

	/* ... Insert generic settings here ... */

	/* (array) Array of choices where the key ('red') is used as value and the value ('Red') is used as label */
	'choices' => array(
		'red'   => 'Red'
	),

	/* (bool) Allow a custom choice to be entered via a text input */
	'other_choice' => 0,

	/* (bool) Allow the custom value to be added to this field's choices. Defaults to 0.
	Will not work with PHP registered fields, only DB fields */
	'save_other_choice' => 0,

	/* (string) Specify the layout of the checkbox inputs. Defaults to 'vertical'.
	Choices of 'vertical' or 'horizontal' */
	'layout' => 0,

);

true_false

$true_false_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Text shown along side the checkbox */
	'message' => 0,

	'default_value' => 0,

	'ui'            => 0,

	'ui_on_text'    => '',

	'ui_off_text'   => '',

);

post (object)

$post_object_field = array(

	/* ... Insert generic settings here ... */

	/* (mixed) Specify an array of post types to filter the available choices. Defaults to '' */
	'post_type' => '',

	/* (mixed) Specify an array of taxonomies to filter the available choices. Defaults to '' */
	'taxonomy' => '',

	/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
	'allow_null' => 0,

	/* (bool) Allow mulitple choices to be selected. Defaults to 0 */
	'multiple' => 0,

	/* (string) Specify the type of value returned by get_field(). Defaults to 'object'.
	Choices of 'object' (Post object) or 'id' (Post ID) */
	'return_format' => 'object',

);

page (object)

$page_link_field = array(

	/* ... Insert generic settings here ... */

	/* (mixed) Specify an array of post types to filter the available choices. Defaults to '' */
	'post_type' => '',

	/* (mixed) Specify an array of taxonomies to filter the available choices. Defaults to '' */
	'taxonomy' => '',

	/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
	'allow_null' => 0,

	/* (bool) Allow mulitple choices to be selected. Defaults to 0 */
	'multiple' => 0,

);

relatioinship

$relationship_field = array(

	/* ... Insert generic settings here ... */

	/* (mixed) Specify an array of post types to filter the available choices. Defaults to '' */
	'post_type' => '',

	/* (mixed) Specify an array of taxonomies to filter the available choices. Defaults to '' */
	'taxonomy' => '',

	/* (array) Specify the available filters used to search for posts.
	Choices of 'search' (Search input), 'post_type' (Post type select) and 'taxonomy' (Taxonomy select) */
	'filters' => array('search', 'post_type', 'taxonomy'),

	/* (array) Specify the visual elements for each post.
	Choices of 'featured_image' (Featured image icon) */
	'elements' => array(),

	/* (int) Specify the minimum posts required to be selected. Defaults to 0 */
	'min' => 0,

	/* (int) Specify the maximum posts allowed to be selected. Defaults to 0 */
	'max' => 0,

	/* (string) Specify the type of value returned by get_field(). Defaults to 'object'.
	Choices of 'object' (Post object) or 'id' (Post ID) */
	'return_format' => 'object',

);

taxonomy

$taxonomy_field = array(

	/* ... Insert generic settings here ... */

	/* (string) Specify the taxonomy to select terms from. Defaults to 'category' */
	'taxonomy' => '',

	/* (array) Specify the appearance of the taxonomy field. Defaults to 'checkbox'
	Choices of 'checkbox' (Checkbox inputs), 'multi_select' (Select field - multiple), 'radio' (Radio inputs) or 'select' (Select field) */
	'field_type' => 'checkbox',

	/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
	'allow_null' => 0,

	/* (bool) Allow selected terms to be saved as relatinoships to the post */
	'load_save_terms'   => 0,

	/* (string) Specify the type of value returned by get_field(). Defaults to 'id'.
	Choices of 'object' (Term object) or 'id' (Term ID) */
	'return_format'     => 'id',

	/* (bool) Allow new terms to be added via a popup window */
	'add_term'          => 1

);

user

$user_field = array(

	/* ... Insert generic settings here ... */

	/* (array) Array of roles to limit the users available for selection */
	'role' => array(),

	/* (bool) Allow a null (blank) value to be selected. Defaults to 0 */
	'allow_null' => 0,

	/* (bool) Allow mulitple choices to be selected. Defaults to 0 */
	'multiple' => 0,

);

Fields (additional)

repeater

Позволяет создавать повторяющийся контент. Этот тип поля выступает в качестве родительского для набора подполей, которые могут повторяться снова и снова. Особенностью этого типа поля является его универсальность - внутри repeater может быть исползован любой тип поля.

Example
'fields'   => [
	[
		'key'               => 'field_scc-repeater-1',
		'label'             => 'Contact Cards',
		'name'              => 'scc-repeater-1',
		'type'              => 'repeater',
		'collapsed'         => '',
		'min'               => 1,
		'max'               => 3,
		'layout'            => 'block', // table, block, row
		'button_label'      => '',
		'sub_fields'        => [
			// base fields: text, image, etc...
			[...],
			[...],
			[...],
		],
	]
],
Options
sub_fields
Defines the set of repeatable sub fields.
collapsed
Sub field key to show when row is collapsed. Ex: 'collapsed' => 'field_7346e9002b5e4',.
min
Sets a limit on how many rows of data are required.
max
Sets a limit on how many rows of data are allowed.
layout

Defines the layout style of the appearance of the sub fields.

  • table: Sub fields are displayed in a table. Labels will appear in the table header.
  • block: Sub fields are displayed in blocks, one after the other.
  • row: Sub fields are displayed in a two column table. Labels will appear in the first column.
button_label
The text shown in the ‘Add Row’ button.
pagination(ACF 6.0)
Defines if the repeater should only load a set number of rows per page when editing the repeater in the admin. If disabled (which it is by default), all rows will be loaded at once. This setting does not affect template usage or results returned via the REST API. Note: This setting is not currently supported inside flexible content and other repeater fields. In these cases, this setting will not be shown.
rows_per_page(ACF 6.0)
Sets the number of rows that are displayed on a page if the “Pagination” setting is enabled.

accordion

group

tab

relationship

clone

Pro: PRO Version only.
Doc: https://advancedcustomfields.com/resources/clone/
See: acf_field_clone{}
Category: layout

flexible_content

--

Офф документация: https://www.advancedcustomfields.com/resources/register-fields-via-php/