How to modify or customize ACF Relationship Search?

ACF Relationship Search uses the default WordPress Search Method. So there is no difference between ACF Relationship search and WordPress Search.

If you have created a relationship field and would like to allow a search to work on a meta query or tax query then you need to work with the filter of ACF.

ACF filter which is related to the Relationship fields is ‘ACF/fields/relationship/query’

Now how one can use this filter to customize Relationship Result?
We need to use ‘pre_get_posts‘ filter when Relationship Search is executed and below snippet shows a basic start for your customization.
Use below code snippet in your functions.php:

/*This filter run before ACF execute query, so that one can hook 'pre_get_posts' filter for modification*/
add_filter('acf/fields/relationship/query', 'add_acf_relationship_pre_get_posts_filter', 10, 3);
function add_acf_relationship_pre_get_posts_filter($args, $field, $post_id) {
  add_filter('pre_get_posts', 'acf_relationship_pre_get_posts_filter');
  return $args;
}

function acf_relationship_pre_get_posts_filter($query) {
  remove_filter('pre_get_posts', 'acf_relationship_pre_get_posts_filter');
  if ($query->is_search()) {
    // modify the query as per your wish as we do with WordPress search like using custom meta query or tax query
  }
}

Leave a Comment

Your email address will not be published. Required fields are marked *