Support

Account

Home Forums Backend Issues (wp-admin) ACF load_field preventing custom taxonomy checkboxes from staying checked

Solved

ACF load_field preventing custom taxonomy checkboxes from staying checked

  • I’m using the following code in functions.php to populate a radio button’s options:

    function acf_load_sector_choices( $field ) {
        
        // reset choices
        $field['radio'] = array();
    
    	$args = array(
    		'post_type'			=> 'page',
    		'post_parent'		=> 691,
    		'posts_per_page'	=> -1,
    		'orderby'			=> 'title',
    		'order'				=> 'ASC'
    	);
    
    	$sectors = new WP_Query($args);
    
    	if( $sectors->have_posts() ) : 
    	
    		while( $sectors->have_posts() ) : $sectors->the_post();
    	
    			// vars
    			$value = get_the_ID();
    			$label = ucfirst( str_replace( 'Fabrication for ', '', get_the_title() ) );
    
    			// append to choices
    			$field['choices'][ $value ] = $label;
    	
    		endwhile; wp_reset_query();
    	
    		$field['choices']['none'] = 'None';
    	
    		$field['default_value'] = 'none';
    	
    	endif; 
    
    	// return the field
        return $field;
        
    }
    
    add_filter('acf/load_field/name=sector_name', 'acf_load_sector_choices');

    On the pages this appears on there is also a list of custom taxonomy (project_cats) checkboxes. The taxonomy choices can be ticked and updated, but when the post is saved, the ticks disappear. In the post list, the selected terms show up as they should in the admin column, but appear unchecked when I edit the post.

    Any thoughts?

  • Didn’t work, but good to know in general!

  • My guess is that the loop in your function is interfering is some way with the global $post value. This can be caused by many things. I actually just had a similar problem on a site myself and it took me a long time to track it down.

    My suggestion, to rule this out, would be to not use have_posts() and the_post() at all and instead to access the post information a different way.

    
    if (count($sectors->posts)) {
      
      foreach ($sectors->posts as $post) {
      
        // vars
        $value = $post->ID;
        $label = ucfirst(str_replace('Fabrication for ', '', $post->post_title));
      
        // append to choices
        $field['choices'][ $value ] = $label;
      
      }
    }
    

    you should not use wp_reset_postdata() if you use the above code

  • John, you clever son-of-a-female-dog, you’ve got it! Thank you so much!

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.