Home › Forums › General Issues › Custom Location Rule for Taxonomies
Hello,
I’m trying to show a field group when a certain custom taxonomy term, or its children, is selected. I know out of the box the Post Taxonomy rule only applies to a single term, so I need to define a custom rule.
I copied most of the code below from the Post Taxonomy rule source code. However, the field group only “flashes” then hides itself again when I select a child term. Totally works if I pick a parent term though.
Any help is appreciated. I’m on PRO v5.3.10. Thanks!
function acf_rule_values_taxonomy_tree( $choices ) {
$choices = acf_get_taxonomy_terms();
// unset post_format
if( isset($choices['post_format']) ) {
unset( $choices['post_format']) ;
}
return $choices;
}
add_filter( 'acf/location/rule_values/taxonomy_tree', 'acf_rule_values_taxonomy_tree' );
function acf_rule_match_taxonomy_tree( $match, $rule, $options ) {
// bail early if not a post
if( !$options['post_id'] ) return false;
$data = acf_decode_taxonomy_term( $rule['value'] );
$term = get_term_by( 'slug', $data['term'], $data['taxonomy'] );
$term_id = (int)$term->term_id;
$term_children = get_term_children($term_id, $data['taxonomy']);
array_push($term_children, $term_id);
// bail early if no term
if( !$term ) return false;
// post type
if( !$options['post_type'] ) {
$options['post_type'] = get_post_type( $options['post_id'] );
}
// get terms
// - allow an empty array (sent via JS) to avoid loading the real post's terms
$terms = $options['post_taxonomy'];
if( !is_array($terms) ) {
$terms = wp_get_post_terms( $options['post_id'], $term->taxonomy, array('fields' => 'ids') );
}
// If no terms, this is a new post and should be treated as if it has the "Uncategorized" (1) category ticked
if( empty($terms) ) {
$terms = array( 1 );
}
// compare
if( $rule['operator'] == "==") {
$match = in_array($terms[0], $term_children);
} elseif( $rule['operator'] == "!=") {
$match = !in_array($terms[0], $term_children);
}
return $match;
}
add_filter( 'acf/location/rule_match/taxonomy_tree', 'acf_rule_match_taxonomy_tree', 10, 3 );
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
CPT registration is coming to ACF! We demoed the new feature during the most recent session of ACF Chat Fridays. Check out the summary for the details. https://t.co/k2KQ3WWBAz
— Advanced Custom Fields (@wp_acf) March 7, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.