Skip to content

Instantly share code, notes, and snippets.

@cfxd
Last active February 9, 2017 22:47
Show Gist options
  • Save cfxd/4d032dac646283ffcb40 to your computer and use it in GitHub Desktop.
Save cfxd/4d032dac646283ffcb40 to your computer and use it in GitHub Desktop.
Add taxonomy hierarchy (parent and child) matching to Advanced Custom Fields
<?php
function add_child_and_parent_to_acf_taxonomy_choices($choices) {
$tax_choices = array();
foreach($choices as $taxonomy => $c) {
$tax_choices[$taxonomy] = $c;
if($taxonomy != 'all' && is_taxonomy_hierarchical($taxonomy)) {
$tax_choices[$taxonomy.'-tax_parent'] = $c.' (parent)';
$tax_choices[$taxonomy.'-tax_child'] = $c.' (child)';
}
}
return $tax_choices;
}
add_filter('acf/location/rule_values/taxonomy', 'add_child_and_parent_to_acf_taxonomy_choices');
function child_and_parent_taxonomy_matching_for_acf($match, $rule, $options) {
global $tag_ID;
$taxonomy = $options['taxonomy'];
if(!$taxonomy) {
return false;
}
if($tag_ID) {
$term_obj = get_term($tag_ID, $taxonomy);
$tax_rule = str_replace($taxonomy.'-', '', $rule['value']);
if($tax_rule == 'tax_parent') {
if($rule['operator'] == "==") {
$match = !$term_obj->parent;
} elseif($rule['operator'] == "!=") {
$match = $term_obj->parent;
}
} elseif($tax_rule == 'tax_child') {
if($rule['operator'] == "==") {
$match = $term_obj->parent;
} elseif($rule['operator'] == "!=") {
$match = !$term_obj->parent;
}
}
} else {
if($rule['operator'] == "==" ) {
$match = ($taxonomy == $rule['value']);
if($rule['value'] == "all") {
$match = true;
}
} elseif($rule['operator'] == "!=") {
$match = ($taxonomy != $rule['value']);
if($rule['value'] == "all") {
$match = false;
}
}
}
return $match;
}
add_filter('acf/location/rule_match/taxonomy', 'child_and_parent_taxonomy_matching_for_acf', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment