Support

Account

Home Forums ACF PRO Dynamically Populate Field + CPTonomy Reply To: Dynamically Populate Field + CPTonomy

  • Found out, literally a minute after posting this. Turns out it was a matter of getting the meta_value first, then setting the field via $my_cpt_field[‘default_value’]

    Here’s the code

    //Populate the Select field, 'My Post Type' (field_1234) with dynamic values
    add_filter('acf/load_field/key=field_1234', function($my_cpt_field) {
    	
    	global $post_id;
    	$post_id = $_GET['exp_id'];	
    	$cptonomy_post_meta = get_post_meta($post_id,'_custom_post_type_onomies_relationship',false);
    	
    	$cptonomy_val1 = $cptonomy_post_meta[0];
    	$cptonomy_val2 = $cptonomy_post_meta[1];
    	
    	// Cptonomy Loop
    	
    	$cptonomy_arr = get_posts( array(
    		'numberposts'		=> -1,
    		'post_type'		=> 'my_post_type',
    		'my-taxo'		=> 'taxo-1',
    		'suppress_filters'	=> false,
    		'orderby'		=> 'title',
    		'order'			=> 'ASC',
    	) );
    	
    	//These can be dynamically generated using any PHP code
    	if( $cptonomy_arr ) {
    		foreach ( $cptonomy_arr as $cptonomy_item ) {
    			$my_cpt_field['choices'][$cptonomy_item->ID] = get_the_title($cptonomy_item->ID); // This populates the select field options fine
    			// How do I set the 'selected' value'?
    			$my_cpt_field['default_value'] = $cptonomy_val2; // this way
    	}
    	
    	return $my_cpt_field;
    });