The first thing I would recommend is reading this article on official ACF website. There is a nice description about all aspects of custom locations.
The Code
To create a custom location rule that allows adding ACF fields to the product categories that are children only, just add the following code to your functions.php file:
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices ) {
$choices[ 'Post' ][ 'taxonomy_term_child' ] = 'Taxonomy Term Child';
return $choices;
}
add_filter('acf/location/rule_values/taxonomy_term_child', 'acf_location_rules_values_taxonomy_term_child');
function acf_location_rules_values_taxonomy_term_child( $choices ) {
if ( $taxonomies = get_taxonomies( array(), 'objects' ) ) {
foreach( $taxonomies as $taxonomy ) {
$choices[ $taxonomy->name ] = sprintf( '%s (%s)', $taxonomy->label, $taxonomy->name );
}
}
return $choices;
}
add_filter('acf/location/rule_match/taxonomy_term_child', 'acf_location_rules_match_taxonomy_term_child', 10, 3);
function acf_location_rules_match_taxonomy_term_child( $match, $rule, $options ) {
// Apply for taxonomies and only to single term edit screen
if ( ! isset( $options[ 'taxonomy' ] ) || ! isset( $_GET[ 'tag_ID' ] ) ) {
return $match;
}
// Ensure that taxonomy matches the rule
if ( ( $rule[ 'operator' ] === "==" ) && ( $rule[ 'value' ] !== $options[ 'taxonomy' ] ) ) {
return $match;
}
elseif ( ( $rule[ 'operator' ] === "!=" ) && ( $rule[ 'value' ] === $options[ 'taxonomy' ] ) ) {
return $match;
}
// Get the term and ensure it's valid
$term = get_term( $_GET[ 'tag_ID' ], $rule[ 'value' ] );
if ( ! is_a( $term, 'WP_Term' ) ) {
return $match;
}
// Apply for those that have parent only
if ( $term->parent ) {
$match = true;
}
else {
$match = false;
}
return $match;
}
New Location Option
Afterwards, you’ll have the following option under Location settings of your Field Group: