Skip to content

Instantly share code, notes, and snippets.

@philbirnie
Last active July 14, 2020 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philbirnie/ba4715bb972b91e31c13e349398a1896 to your computer and use it in GitHub Desktop.
Save philbirnie/ba4715bb972b91e31c13e349398a1896 to your computer and use it in GitHub Desktop.
Custom Filter for ACF (Show Fields on Single Taxonomy Page)
<?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