Support

Account

Home Forums General Issues Custom Location Rule for Taxonomies

Solved

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 );
  • John, you have saved my life! Thank you!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.