Support

Account

Home Forums Backend Issues (wp-admin) Calculated ACF fields conflict with acf/format_value

Solved

Calculated ACF fields conflict with acf/format_value

  • Hello,

    I have a group of ACF number fields on an Options page for basic automatic calculations. All field values (entered and calculated) are then output to pages/posts using ACF shortcodes. Everything works great…until I add an acf/format_value function to format all numbers with commas. My understanding is that ACF/format_value only runs on the front end of the website. However, once my function is enabled, my calculated fields on the Options page are incorrect. I have a feeling I am missing something very basic – any suggestions are greatly appreciated.

    Below is an example of the code I am using.

    
    add_action('acf/save_post', 'count_my_pets', 5);
    
    function count_my_pets($post_id)
    {
    	$post_id = "options";
    
    	// ACF Option page field values.
    	$dogs = get_field('my_dogs', 'options');
    	$cats = get_field('my_cats', 'options');
    	$birds = get_field('my_birds', 'options');
    
    	// Calculate total pets.
    	$pets_total = $dogs + $cats + $birds;
    
    	// Update ACF field for total_pets.
    	update_field('total_pets', $pets_total, $post_id);
    }
    
    add_filter('acf/format_value/type=number', 'format_numbers', 10, 3);
    
    function format_numbers($value, $post_id, $field)
    {
    	$value = number_format($value);
    	
    	return $value;
    }
    
  • The issue is that the function to format the value is being used when you use get_field in your save post action. This means that the calculation is attempting to do the the calculation with formatted value.

    To overcome this you need to tell ACF not to format the values. This is done by adding the 3rd argument to get_field(), example:

    
    $dogs = get_field('my_dogs', 'options', false);
    
  • John – I cannot thank you enough. You sir, are a rock star. I had a feeling that ACF was formatting the values, but was not aware of the 3rd argument to disable (inexperience on my part). I just updated my code and everything is working great. Best wishes to you!

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

You must be logged in to reply to this topic.