Support

Account

Home Forums General Issues Formatting number fields using format_value

Solving

Formatting number fields using format_value

    • alissit

    • February 13, 2020 at 11:46 pm

    Was wondering if anyone could help.
    I’m formatting a lot of number fields on my site using the following code:

    add_filter('acf/format_value/name=property_latest_valuation', 'fix_number', 20, 3);
    function fix_number($value, $post_id, $field) {
      $value = number_format($value);
      return $value;
    	}

    Is there any way to use this handy bit of code to output a large number of number fields? Using an array? I’m not sure how to implement that in the code. I’m learning as I go along here.

    I’d format all the number fields, but there are a couple that don’t need the comma.

  • There are several alternatives

    If this was something I wanted to do on a large scale but did not want to have it run on all number fields I would add a custom setting to number fields https://www.advancedcustomfields.com/resources/adding-custom-settings-fields/

    Then I would create a format_value filter for all number fields that tested the new setting to see if the number should be formatted.

    Or, if there are only a few fields that should not be formatted then I would create the filter for all number fields like the one you have and I would check $field['key'] and not format those.

    Alternately, you could set up an array in your filter

    
    add_filter('acf/format_value/type=number', 'fix_number', 20, 3);
    function fix_number($value, $post_id, $field) {
      $keys = array(
        // list of field keys to format
        'field_XXXXXXX',
        'field_YYYYYYY',
        // etc...
      );
      if (in_array($field['key'], $keys)) {
        $value = number_format($value);
      }
      return $value;
    }
    
    • alissit

    • February 14, 2020 at 5:27 am

    Perfect, thank you so much.
    I’ll try out your suggestions and go from there.

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

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.