Created
March 23, 2017 10:02
-
-
Save yratof/9bc932e879bec666b40e8727dfa97b43 to your computer and use it in GitHub Desktop.
Filter ACF post_object by taxonomy when on 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 | |
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