Support

Account

Home Forums General Issues ACF field that returns value, based on date formula (years since ACF date field)

Helping

ACF field that returns value, based on date formula (years since ACF date field)

  • Working on a custom post type for team members, we’re looking to output the number of years someone has been with a company.

    There is a date field that we fill out for the person’s “Start Date”. But we want to have a separate field (for use later on in the custom post type frontend output) that will always display the number of years since that date. E.g., the (uneditable) custom field would basically be a formula that says:

        Years between Start Date and Now

    I know how to do a PHP function (via a shortcode) that would be able to output that number. But for specific reasons, I’d like it to actually be stored within an ACF field for each person. And the field value would of course need to be automatically updated each day (and not only on “save” of that post).

    So, is there a way to take a custom field’s date value, and output a new value [after customizing that value with PHP] within a different custom field, based on the other field?

  • acf/format_value

    
    add_filter('acf/format_value/name=years_employed', 'calculate_years_employed', 20, 3);
    function calculate_years_employed($value, $post_id, $field) {
      // don't really care what the value is
      $start_date = get_field('start_date', $post_id);
      $value = calculate how long from start date...
      return $value;
    }
    

    this has not been tested at all, but I am pretty sure that the field I’m calling “years_employed” and be a text field with no value at all that is never stored. Because we are ignoring whatever value this field might have and generating a new formatted value.

    This could also be accomplished with an acf/load_value filter.

    Just one note. In order to use either of these filters with the field name the field must actually exist in the DB event if the field has no value.

    If you wanted, for completeness, you could create and acf/save_post filter that would automatically populate the value, but like I said, I think it would work fine using a text field where an empty value is stored in the DB.

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

You must be logged in to reply to this topic.