Home › Forums › Backend Issues (wp-admin) › Relationship field – filter choices with AJAX › Reply To: Relationship field – filter choices with AJAX
I managed to change the arguments for the relationship field, and get the result based on them. Task: I have Users, And I also have CPT Teams – when creating a user, I assign him a role, for example: Reporter and I, in the relation field, should pull up Teams whose selection field is equal to Reporter.
JS:
acf.addFilter('relationship_ajax_data', function (ajaxData, field){
if(ajaxData.field_key == "field_63599162ef1ea"){
if($('body div[data-key="field_6315dc672e038"]').length > 0){
let roles = [];
$('body div[data-key="field_6315dc672e038"] .acf-checkbox-list li input').each(function (i,e){
if($(this).is(':checked')){
roles.push($(this).val());
}
});
ajaxData.meta_key = 'team_role';
ajaxData.meta_value = roles;
}
console.log(ajaxData);
}
return ajaxData;
});
PHP
add_filter('acf/fields/relationship/query/name=user_teams', [$this, 'lh_acf_fields_relationship_query'], 10, 3);
public function lh_acf_fields_relationship_query($args, $field, $post_id)
{
if(isset($_POST) && !empty($_POST)){
if(isset($_POST['field_key']) && $_POST['field_key'] == 'field_63599162ef1ea'){
if(isset($_POST['meta_key']) && !empty($_POST['meta_key']) &&
isset($_POST['meta_value']) && !empty($_POST['meta_value'])){
$args['meta_query'] = [
'relation' => 'AND',
[
'key' => sanitize_text_field($_POST['meta_key']),
'value' => $_POST['meta_value'],
'compare' => 'IN'
]
];
}
}
}
return $args;
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.