Last active
February 9, 2017 22:47
-
-
Save cfxd/4d032dac646283ffcb40 to your computer and use it in GitHub Desktop.
Add taxonomy hierarchy (parent and child) matching to Advanced Custom Fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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