Skip to content

Instantly share code, notes, and snippets.

@SteveJonesDev
Created October 20, 2023 19:17
Show Gist options
  • Save SteveJonesDev/61cb76d2aef7a9e7a5f130bb17257ab1 to your computer and use it in GitHub Desktop.
Save SteveJonesDev/61cb76d2aef7a9e7a5f130bb17257ab1 to your computer and use it in GitHub Desktop.
ACF Post Object Field Term Filter
<?php
/**
* Filters the query arguments for the 'featured_posts' ACF Post Object field.
* The filter limits the displayed posts to those associated with the currently edited/viewed term
* for the taxonomies: 'category', and 'post_tag'.
*
* @param array $args The WP_Query arguments.
* @param array $field The field settings.
* @param int $post_id The post ID (or term ID, depending on context).
*
* @return array Modified query arguments.
*/
function sjd_filter_post_object_query( $args, $field, $post_id ) {
// Check if this is the specific field we want to modify.
if ( 'featured_posts' === $field['name'] ) {
// Check if it's a term ID and extract the ID.
if ( strpos( $post_id, 'term_' ) === 0 ) {
$term_id = str_replace( 'term_', '', $post_id );
$term = get_term( $term_id );
// Check if term belongs to the specified taxonomies.
if ( $term instanceof WP_Term && in_array( $term->taxonomy, [ 'category', 'post_tag' ], true ) ) {
$args['tax_query'] = [
[
'taxonomy' => $term->taxonomy,
'field' => 'term_id',
'terms' => $term->term_id,
'operator' => 'IN',
],
];
}
}
}
return $args;
}
add_filter( 'acf/fields/post_object/query', 'sjd_filter_post_object_query', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment