Advanced Custom Fields (ACF)
Slices
At Built By Cactus we like code to be as DRY as possible, therefore we use a slice structure in our themes. Using slices enables us to repeat code as little as possible when developing.
ACF
When setting up slices, we should add our ACF fields into an inactive field group prefixed with [Template]
.
This allows us to keep the actual field groups and our slice groups separate and means if we need to change a slice, we have a single place to do it.
These template field groups can then be pulled in to an active field group by using a clone field.
You can either clone as is, so the fields will hold the same name field = text
or prefix it with the clone field name,
which is useful if using that slice more than once on a page field = header_text
.
See below for an example of a template field group:
This is how the usage of a template will look:
PHP
PHP When writing slices in PHP we don’t access any of our ACF fields in the template and instead prefer for them to be passed in as arguments. This way if we need to pass in hard coded text we can easily do that.
We should check for arguments at the top of the file and set a sensible default if they’re not pre-set. A general slice should look something like this:
<?php
$text = $text ?? '';
$image = $image ?? '';
$date = $date ?? false;
$modifier = $modifier ?? '';
?>
<div class="image-slice d-flex align-items-center {{ $modifier }}" style="background-image: url('{{ $image }}')">
<div class="image-slice__text align-self-end">
<div class="container">
<div class="row">
@if($date)
<div class="col-12 image-slice__date">
{{ $date }}
</div>
@endif
<div class="col-12">
{{ $text }}
</div>
</div>
</div>
</div>
</div>
We can use a slice as follows:
@include('slices.header', [
'text' => get_field('header_text'),
])
or we can pass through more arguments
@include('slices.header', [
'text' => get_field('header_text'),
'title' => 'Home',
'modifier' => 'header-slice--light'
])
Writing our PHP in this way means that we should be as DRY as possible and speed up development in the long run!
ACF Gutenberg Blocks
ACF also gives us a really easy way to create gutenberg blocks. You can read more about that here.