Skip to content

Instantly share code, notes, and snippets.

@yratof
Created March 23, 2017 10:02
Show Gist options
  • Save yratof/9bc932e879bec666b40e8727dfa97b43 to your computer and use it in GitHub Desktop.
Save yratof/9bc932e879bec666b40e8727dfa97b43 to your computer and use it in GitHub Desktop.
Filter ACF post_object by taxonomy when on taxonomy page
<?php
class acf_filter_post_object {
static function setup() {
add_filter( 'acf/fields/post_object/query/name=FIELD_NAME', __CLASS__ . '::only_current_terms', 10, 3 );
}
/*
Only current terms to be shown within the taxonomy
page for the post_object type of selection
*/
static function only_current_terms( $args, $field, $post_id ) {
// Due to the AJAX request, there's not a way
// to get the query to work without doing some
// dangeous sniffing
$url = parse_url( @$_SERVER['HTTP_REFERER'] );
if ( ! $url || ! isset( $url['query'] ) ) {
return $args;
}
// Get the query, split it into an array
parse_str( $url['query'], $query );
if ( empty( $query ) ) {
return $args;
}
// Check that it contains the right taxonomy
if ( 'product_cat' !== @$query['taxonomy'] ) {
return $args;
}
// Check if theres an ID involved
$term_id = (int) @$query['tag_ID'];
if ( ! $term_id ) {
return $args;
}
// Add a tax query to filter out all products
// that aren't in this specific category
$args['tax_query'] = [[
'taxonomy' => 'product_cat',
'fields' => 'id',
'terms' => $term_id,
]];
return $args;
}
}
__CLASS__::setup();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment