I have a wordpress site with custom post types that are people. They include a variety of custom field descriptors - one of which is Date of bith.

I have the date of birth field in place (via Advanced Custom fields) and have displayed it on the front end via adding code to my functions.php file:

function age_in_years() {
$year_of_birth = get_field( 'date_of_birth', $modelID );
return intval( date( 'Y', time() - strtotime( $year_of_birth ) ) ) - 1970;

However, I would also like to be able to filter these custom post types based on an age range (I am using FacetWP, but happy to look elsewhere) - since the age is just a front end display, I can't filter on an age - can anyone point me in the right direction? I know with Advanced Custom fields there's the update_field() option, but I'm lost as to how to make it work to grab the age from the date of birth and save it to the database ready to be referenced for filtering.

Thanks very much.


In order to be able to query by age, you will need to create another custom hidden field to store the date.

You can then hook into the acf/save_post hook with a priority higher than 10 in order to update the age field value whenever the field is created/updated.

Here is a gist of the code that should work


function my_acf_save_post($post_id)

    // check if post type is persons
    $post_type = get_post_type($post_id);
    if ($post_type != 'people') {
        //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_field', $age);


// run after ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 20);

  • Patrizio, you are amazing! worked like a dream! – shugar Oct 25 '16 at 2:14
  • No problem @shugar glad to help :) – Patrizio Mwange Oct 25 '16 at 7:03
  • @shugar: please mark the post as answered as it helps address your very challenge as you rightly confirmed above. – nyedidikeke Mar 14 '17 at 8:41
  • The age will be wrong after 1 year. – Joel James Aug 1 '19 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.