Home › Forums › Backend Issues (wp-admin) › How can I send an additional field during ajax requests? › Reply To: How can I send an additional field during ajax requests?
Thanks this helped me get to my own solution 🙂
For anyone in need this is how I solved a scenario where the user first selects a post object (post object field) and then selects a term from a taxonomy field which should only show terms connected to the previously chosen post.
This works on 5.3.n and the JS is a bit different now so I think you might need to change the JS even for the solution above.
*php*
/**
* Filters the idrott taxonomy dropdown by selected club.
*
* @since 1.0.0
*/
public function filter_idrott_dropdown_admin( $args, $field, $post_id ){
$club = isset($_REQUEST['club_sport']) ? (int) $_REQUEST['club_sport'] : false;
if ( !$club ){
return $args;
}
$sports = get_the_terms( $club, 'idrotter' );
$sport_ids = array();
if( $sports ){
foreach( $sports as $sport ){
$sport_ids[] = $sport->term_id;
}
}
if( !empty( $sport_ids ) ){
$args['include'] = $sport_ids;
}
return $args;
}
*Jquery/javascript*
/**
* Update the ajax arguments for select2 objects to include the chosen club id
* This is done by replacing the default ajax.data function with a wrapper, which calls the old function and then appends "club_sport" to the results.
*/
acf.add_filter(
'select2_args',
function( args ) {
if ( typeof args.ajax.data == 'function' ) {
var old_data_func = args.ajax.data; // We'll keep this for maximum compatibility, and extend it.
args.ajax.data = function(term, page) {
var default_response = old_data_func( term, page ); // Call the old, default function.
default_response.club_sport = $('#acf-field_577e458143db1-input').val();
// Return the default args with our club_sport value.
return default_response;
}
}
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.