Support

Account

Home Forums Backend Issues (wp-admin) Conditionally registering field on acf/update_value Reply To: Conditionally registering field on acf/update_value

  • It turns out you can call acf_update_field with almost the same parameters as acf_add_local_field, except I just had to pass the parent as a post_id. Here’s the (simplified) code that I used:

    function get_acf_group_id($group_name){
        global $wpdb;
    
        return $wpdb->get_var("
            SELECT ID
            FROM $wpdb->posts
            WHERE post_type='acf-field-group' AND post_excerpt='$group_name';
        ");
    }
    
    function my_field_registration( $value, $post_id, $field  ) {
    
        if ( $field['name'] == 'my_triggering_field' ) {
        	if ( $some_condition ) {
    			$args = array(
    				'key' => 'field_' . uniqid();,
    				'label' =>  'Field label',
    				'name' => 'my_new_field_name',
    				'type' => 'number',
    				'parent' => get_acf_group_id('my-field-group-name') // hyphenated!
    			);
    			acf_update_field($args);
    		}
        }
    
        return $value;
        
    }
    
    add_filter('acf/update_value', 'my_field_registration', 10, 3);

    This creates a field programmatically in the database which is editable in the admin.