Auto Populate Field Based On Calculation

Support General Auto Populate Field Based On Calculation

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #38831
    ZakirZakir
    Participant

    Hi,

    I am looking for a way to do the following

    1. Create a Custom Post Type called Profile
    2. Create Custom Fields, two of which will be "Date of Birth" and "Age"
    3. Ask the user to input their "Date of Birth" only
    4. Automatically calculate the user's age (Age = Current Date - Date of Birth) and store it in the profile's "Age" field upon submission
    5. Everyday, automatically update the age field to correctly reflect the user's age
    6. Use WPGridBuilder Facets to filter for Age on the frontend using the Age field which is auto calculated regularly.

    Is this possible?

    #38845
    Long NguyenLong Nguyen
    Moderator

    Hi,

    It is possible to update a field value based on another field value when saving the post. You can use the action hook rwmb_after_save_field to do that. Please read more on the documentation https://docs.metabox.io/actions/rwmb-after-save-field/

    #38857
    ZakirZakir
    Participant

    Thank you for the response. So if I understand correctly, I can use a Code Snippet to write a function that checks the current date and also pulls the Date of Birth. Pseudo code below.

    //Check if the month and date of the current date is equal to the month and date of the date of birth as a condition to update the age field
    If ( (Month(currentDate)).(Day(currentDate)) = (Month(dateOfBirth)).(Day(dateOfBirth))) {
    $age = currentDate - dateOfBirth
    }

    do_action( 'rwmb_after_save_field', $null, $field, $age, $old, $object_id );

    Is this correct?

    #38867
    Long NguyenLong Nguyen
    Moderator

    Hi,

    For example: the field Date Of Birth has the ID date_of_birth and the field Age has the ID age, the code to update the field age after saving the field date_of_birth should be:

    add_action( 'rwmb_date_of_birth_after_save_field', function ( $null, $field, $new, $old, $object_id ) {
        // $new is the date_of_birth field value
        $age_value = $new; // your function to calculate the age here
        update_post_meta( $object_id, 'age', $age_value);
    }, 10, 5 );
    #42610
    BNBN
    Participant

    Hello Zakir,

    I am exactly in the same situation as your original post. Did you manage to get this done? I would appreciate if you can guide me please?

    Thank you!

    #46233
    FizzPop MediaFizzPop Media
    Participant

    I am attempting to do something similar to this where I need to set the value of total_baths when an entry is saved. total_baths needs to be the total of full_baths and half_baths

    Can you provide instructions on how I would update the value of total_baths based on the value of the two other fields?

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.