Custom location rules

Overview

New to v3.5.7 is the ability to add custom location rules. Location rules are used by ACF to decide whether or not to show a field group when editing a page / post.

Adding a custom location rule consists of 4 steps:

1. Add custom types

When editing a field group, the ‘types’ drop down is the first dropdown in the location rule row.

Note that the list is broken into groups. This is important to keep in mind when editing the choices for this dropdown. Use the ‘acf/location/rule_types’ filter to customize this list. Here is an example of adding “user” to the ‘Basic’ group in the dropdown choices:

3. Add custom values

When editing a field group, the ‘values’ drop down is the third dropdown in the location rule row. This list is dynamically updated based on the ‘type’.

This list must have a choice to select from. To populate this list, use the ‘acf/location/rule_values/$type’ filter. Please note that the variable $type in the filter name should match the ‘type’ value.

This code will populate the list with all the available users. The list will save the user_id but display the user display_name:

4. Matching the rule

After following the above steps, you should now have a custom location rule applied to your field group. The last step is to create a function for matching this rule to an edit screen.

When viewing an edit screen (page / post / user / taxonomy / attachment / etc), ACF will find all available field groups and run matching functions on the field group’s location rules. These matching functions will return either true or false and determine if a field group gets shown or not.

To create a location rule_match function for your custom location rule, use the ‘acf/location/rule_match/$type’ filter. Please note that the variable $type in the filter name should match the ‘type’ value.

This filter accepts 3 parameters:

$match – the true / false variable which must be returned

$rule – the current rule that you are matching against. This is an array with keys for ‘param’, ‘operator’, ‘value’.

$options – an array of data about the current edit screen (post_id, page_template, post_type, etc). This array will also include any data posted in an ajax call (ajax calls are made on a post / page when you change the category, page_template, etc)

The following code will create a rule_match for ‘user’ where if the current_user is equal to the user selected (in the field group’s rule) the field group will be shown (unless another rule did not match)