Support

Account

Home Forums ACF PRO udpating Select2 initial choices to match database field

Solved

udpating Select2 initial choices to match database field

  • I’m working on creating bidirectional term relationship fields. There’s a taxonomy multi-select field called related_terms, and when a term is saved with some relationships selected, I want to update those terms’ related_terms fields to include the saved term’s ID. I’m using update_term_meta() to save the related_terms array.

    I have the related term ID array saving correctly to the database; it’s serialized just like terms selected through the interface. But when I refresh the edit term screen for the related term, Select2 isn’t recognizing the selected options. They’re selected correctly in the hidden field, and I can see them flash by in the form before Select2 loads, but then the field appears empty.

    Have I missed something involving caching, or do I need to reinitialize Select2…?

  • Asking the question in public is always the fastest way to find the answer yourself. 😉 This needs some refinement, but setting the $field[‘default_value’] in a acf/load_field hooked function that runs after most other things is working:

    add_filter('acf/load_field/type=taxonomy', function( $field ) {
         
    	$screen = get_current_screen();
    	if ( $screen->base = 'term' && $screen->parent_base == 'edit' ) {
    		$term_id = (int) $_REQUEST['tag_ID'];
    	    $field['default_value'] = get_term_meta( $term_id, $field['name'] );
    	}
      
        return $field; 
        
    }, 99, 1);
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.