Last active
July 14, 2020 21:38
-
-
Save philbirnie/ba4715bb972b91e31c13e349398a1896 to your computer and use it in GitHub Desktop.
Custom Filter for ACF (Show Fields on Single Taxonomy Page)
This file contains 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 "Specific Category" Selector to ACF Interface | |
* | |
* @param array $choices Existing choices. | |
* | |
* @return array Updated choices. | |
*/ | |
function esc_acf_location_rule_post_category( $choices ): array { | |
$choices['Forms']['specific_category'] = __( 'Specific Category', 'esc' ); | |
return $choices; | |
} | |
add_filter( 'acf/location/rule_types', 'esc_acf_location_rule_post_category' ); | |
/** | |
* Adds value to Selection Column in Interface. | |
* | |
* @param array $choices Existing Choices. | |
* | |
* @return array | |
*/ | |
function esc_acf_location_rule_post_category_values( $choices ): array { | |
$categories = get_terms( | |
[ | |
'taxonomy' => 'category', | |
'hide_empty' => false, | |
] | |
); | |
if ( $categories ) { | |
return array_reduce( | |
$categories, | |
function ( $aggregate, \WP_Term $category ) { | |
$aggregate[ $category->term_id ] = $category->name; | |
return $aggregate; | |
}, | |
[] | |
); | |
} | |
return $choices; | |
} | |
add_filter( 'acf/location/rule_values/specific_category', 'esc_acf_location_rule_post_category_values' ); | |
/** | |
* Verifies Comparison on Edit Page | |
* | |
* @param bool $match Current Match Value. | |
* @param array $rule Rule Values (set from group or via PHP). | |
* @param array $options Additional Options Values. | |
* | |
* @return bool True if matches; false otherwise. | |
*/ | |
function esc_acf_location_match_post_category( $match, $rule, $options ) { | |
if ( ! isset( $options['taxonomy'] ) || 'category' !== $options['taxonomy'] ) { | |
return $match; | |
} | |
/* Get Current Page */ | |
$term_id = (int) esc_attr( $_GET['tag_ID'] ?? 0 ); | |
$rule_term_id = $rule['value'] ?? 0; | |
if ( ! is_numeric( $rule['value'] ?? '' ) ) { | |
$rule_term = get_term_by( 'slug', $rule['value'], 'category' ); | |
$rule_term_id = $rule_term ? $rule_term->term_id : 0; | |
} | |
if ( '==' === $rule['operator'] ) { | |
$match = (int) $rule_term_id === $term_id; | |
} elseif ( '!=' === $rule['operator'] ) { | |
$match = (int) $rule_term_id !== $term_id; | |
} | |
return $match; | |
} | |
add_filter( 'acf/location/rule_match/specific_category', 'esc_acf_location_match_post_category', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment