ACF Relationship Field Search Filtering [closed]

First, read this post to understand my answer Search that will look in custom field, post title and post content

You may want to use the acf/fields/relationship/query/ however, when adding the args:

$args['meta_query'] = array(array(
     'key' => 'your_meta',
     'value' => $args['s'],
     'compare' => 'LIKE',
));

you will find that using that query, WordPress will search the posts that contains your search string in the title AND in the meta field.

So you have to add a couple of filters to make this works:

function search_custom_meta_acf_add_join($joins) {
    global $wpdb;
    remove_filter('posts_join','search_custom_meta_acf_add_join');
    return $joins . " INNER JOIN {$wpdb->postmeta} as CMS15 ON ({$wpdb->posts}.ID = CMS15.post_id)";
}

function search_custom_meta_acf_alter_search($search,$qry) {
    global $wpdb;
    remove_filter('posts_search','search_custom_meta_acf_alter_search',1,2);
    $add = $wpdb->prepare("(CMS15.meta_key = 'your_field_name' AND CAST(CMS15.meta_value AS CHAR) LIKE '%%%s%%')",$qry->get('s'));
    $pat="|\(\((.+)\)\)|";
    $search = preg_replace($pat,'(($1 OR '.$add.'))',$search);
    return $search;
}
function modify_acf_relationship_search_query ($args, $field, $post ) {
    add_filter('posts_join','search_custom_meta_acf_add_join');
    add_filter('posts_search','search_custom_meta_acf_alter_search',1,2);
    return $args;
}
add_filter('acf/fields/relationship/query/name=your_field_name', 'modify_acf_relationship_search_query', 10, 3);

What this code does is, basically, to modify the Query that searches the posts since ACF uses the wordpress built-in search functionality for searching in the relationship field. You don’t have to worry about the filters that modifies the search query because they remove themselves when used.

According to the answer I cited above, he doesn’t use a custom table name in the inner join but I did so it doesn’t cause any trouble if you still want to use the $args[‘meta_query’] parameter for a more refined filtering.

Leave a Comment