Check out my age range is matching or not with the ‘date of birth’ stored in database

I’m using custom post type to creating users in my wordpress website. I’m integrating an advance search for list down the users. In that case I need to search user by age ranges like 21 - 30 31 - 40, But I only have the date of birth of users in the DB. As you know in wordpress posts, it’s stored as meta_key and meta_value in the wp_postmeta table.

I’m writing my own custom query to the search part:

Read More
$queryStr = "SELECT DISTINCT ID, wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id";

//if nationality is not empty check it in the DB 
if($sltNationality != '' && $sltNationality != 'Any') :
    $queryStr .= " AND wpostmeta.meta_key = 'nationality' AND wpostmeta.meta_value = '$sltNationality'";
endif;

//if age range is not empty check it
if($age != '' && $age != 'Any') :
    $queryStr .= " check age between condition ";
endif;

//execute
$pageposts = $wpdb->get_results($queryStr, OBJECT);

Now I’m stucked in the age section. As search from the internet, glad I found a code from stackoverflow. get age from DOB

But have no idea how to use this inside my custom query. Please help me guys. thanks

Related posts

1 comment

  1. You should let WordPress build that meta query for you – you can use get_posts to achieve this.

    Here is a suggestion :

    $meta_query = array();
    if($sltNationality != '' && $sltNationality != 'Any') { // nationality query
        array_push($meta_query, array(
            'key'       => 'nationality',
            'value'     => $sltNationality
        ));
    }
    if($age != '' && $age != 'Any') { // age query
        // assuming your select values are always in this format : 21 - 30, 31 -40 etc.
        $age = explode(' - ', $age); 
        $min_year   = (int)date('Y') - (int)$age[1];
        $max_year  = (int)date('Y') - (int)$age[0];
        // build a regex to get all the birth date in the year range
        $year_regex = array();
        for($y = $min_year; $y < $max_year; $y++) {
            array_push($year_regex, strval($y));
        }
        array_push($meta_query, array(
            'key'       => 'age',
            'value'     => '^[0-9]{2}-[0-9]{2}-('.implode('|', $year_regex).')$',
            'compare' => 'REGEXP'
        ));
    }
    $args = array(
        'posts_per_page' => -1,
        'post_type' => 'user',
        'meta_query' => $meta_query
    );
    $users = get_posts($args);
    

    You should check that the post_type name is ok, and that the select values are always matching the “YY – YY” format – if not you will have to do some special conditions.

Comments are closed.