Регистрация полей через 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{}

Below is a list of available generic settings for a field. In addition to these generic settings, each field is also given field type specific settings which are listed down the page.

$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
conditional_logic(mixed)
Conditionally hide or show this field based on other field's values. Best to use the ACF UI and export to understand the array structure.
По умолчанию: 0
wrapper(array)
An array of attributes given to the field element.
По умолчанию: []
default_value(mixed)
A default value used by ACF if no value has yet been saved.
По умолчанию: null

text

$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



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,

);

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,

);

--

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