It’s been a little while, but I wanted to build onto what ChrisAtMogul started here because this worked wonders for me, but I had to do some tweaking to get it to work the way I needed it.
Chris’s code is good for working with one multiselect field, because it allows you to whittle your results in the same field down. However, what I wanted to do was to select a parent taxonomy term in a select, and then have another ACF field directly after that only listed the child terms. That way, they could be pulled from ACF as distinct entities if need be.
So, this requires two fields, both assigned the Taxonomy type. And please note that this is only a singluar level parent/child relationship. Any further, and you’d need to add more to the JS and to the PHP to make this cascade into grandchildren, etc.
jQuery/Javascript
(function($){
$(document).ready( function() {
acf.add_filter('select2_ajax_data', function( data, args, $input, field, instance ){
var parent_field_key = 'field_5f4fcb8f3a1a2'; // Parent Field
var target_field_key = 'field_5f4fd4201446c'; // Child Field
if( data.field_key == target_field_key ){
var field_selector = 'select[name="acf[' + parent_field_key + ']"]'; //the select field holding the values already chosen
if( $(field_selector).val() != '' && $(field_selector).val() != null ){
parent_id = $(field_selector).val();
} else{
parent_id = 0; //nothing chosen yet, offer only top-level terms
}
data.parent = parent_id;
}
return data;
});
});
})(jQuery);
Functions file
function custom_acf_taxonomy_hierarchy( $args, $field, $post_id ){
$parent_id = false;
if ( $field['key'] == 'field_5f4fcb8f3a1a2' ) { // Parent
$parent_id = 0;
} else if ( $field['key'] == 'field_5f4fd4201446c' && !empty( $_POST['parent'] ) ) { // Child
$parent_id = (int)$_POST['parent'];
}
if ( $parent_id !== false ) {
$args['parent'] = $parent_id;
}
return $args;
}
add_filter('acf/fields/taxonomy/query/key=field_5f4fcb8f3a1a2', 'custom_acf_taxonomy_hierarchy',10,3); // Parent
add_filter('acf/fields/taxonomy/query/key=field_5f4fd4201446c', 'custom_acf_taxonomy_hierarchy',10,3); // Child
I hope this manages to help someone like ChrisAtMogul’s code helped me. Thanks again!
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!
ποΈ Just one more day until the next session of ACF Chat Fridays! Make sure to register for the latest updates on whatβs coming in ACF 6.1!
— Advanced Custom Fields (@wp_acf) March 30, 2023
π Friday 31st March 3pm UTC
π Register here - https://t.co/3UtvQbDwNm pic.twitter.com/7xtEJakeQN
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.