Skip to content

Registering Advanced Custom Fields

Brian McCoy edited this page Feb 23, 2018 · 7 revisions

Intro

Alloy Core provides wrapper functions for the ACF PHP functions. There are a couple of reasons for this:

  • It streamlines the addition of fields
  • It reduces the overall code footprint

Registering the fields via PHP is preferred versus the WordPress GUI simply for the fact it makes them extremely portable and reusable. You can copy and paste them from template to template or project to project. When you deploy to staging or production you don't have to worry about messing with the database or any importing to get your fields.

Creating your custom fields file

Custom fields are defined under app/custom-fields. Each file in this directory is automatically loaded so you just need to have your file present. In these examples we'll be adding a basic contact page. So you'd create a file called template-contact.acf.php.

Defining your field group

The first thing you'll need to do is set your group options. There are quite a few options you can set but generally you'll just use title, location and hide_on_screen if you're removing things from the UI. You can add any other group options ( see the ACF documentation ) but this is all that's required to get started. Let's work on our contact page:

$group_args = [
	'title'          => 'Contact Page Options',
	'location_is'    => [ 'page_template', 'template-contact.php' ],
	'hide_on_screen' => [ 'the_content' ]
];

You can see we set hide_on_screen to the_content since we won't have any content sections on the contact page.

Setting the Location

Alloy Core makes it easy to set your location if it's a one to one set up through a location_is parameter. For example, if you just need to set it to the front page you'd do:

'location_is' => [ 'page_type', 'front_page' ]

Where it gets complicated is when you need multiple location rules. To do that you'd use the standard ACF location parameter:

'location'    => [
	[
		[
			'param' => 'page_type',
			'operator' => '!=',
			'value' => 'posts_page'
		],
		[
			'param' => 'page_type',
			'operator' => '!=',
			'value' => 'front_page'
		],
		[
			'param' => 'page_template',
			'operator' => '==',
			'value' => 'default'
		]
	]
]

Clone this wiki locally