Home Forums General Issues Update Age Every Day


Update Age Every Day

  • I have 2 fields:

    • date_of_birth
    • age

    How do I create a daily cron function to check and update the age field?

    Currently, I am using this code to update the age whenever I update my custom post.

    function my_acf_save_post($post_id)
        // check if post type is persons
        $post_type = get_post_type($post_id);
        if ($post_type != 'talent') {
            //return if its not a people post type
        // get year of birth value
        $year_of_birth = get_field('date_of_birth', $modelID);
        //calculate the value of age
        $age = intval(date('Y', time() - strtotime($year_of_birth))) - 1970;
        // update the age field
        update_field('age', $age);
    // run after ACF saves the $_POST['acf'] data
    add_action('acf/save_post', 'my_acf_save_post', 20);
  • Your cron would need to get every post of that post type and loop through them get the dob field and update the age field.

    Wouldn’t it be easier to just calculate the age whenever you need it rather than store it as a value?

  • I am building a talent management page. Clients can filter talents by age. That’s why I need the age to be an accurate value.

  • If your database of talent grows it is very likely that your cron will time out with all the queries that would need to be performed to update every age. For a large DB your cron would need to be set up on the server, no by using WP cron functions and would also likely need to be created in a way that checks how long it’s been running or is some other way be built so that the task can be done over several cron calls.

    I would still use the date field. Let’s say that someone wants to only see people that are over 30 or over.

    // format a date to string to search for
    $query_date = date('Ymd', strtotime('-30 Years'));

    then the meta query

    $meta_query = array(
        'key' => 'date_of_birth',
        'value' => $query_date,
        'compare' '<='
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Update Age Every Day’ is closed to new replies.