php - 检查我的年龄范围是否与数据库中存储的 'date of birth' 匹配

标签 php mysql custom-post-type wordpress

我正在使用自定义帖子类型在我的 wordpress 网站中创建用户。我正在集成对用户列表的高级搜索。在那种情况下,我需要按年龄范围搜索用户,例如 21 - 30 31 - 40,但我在数据库中只有用户的出生日期。正如您在 wordpress 帖子中所知,它在 wp_postmeta 表中存储为 meta_keymeta_value

我正在为搜索部分编写自己的自定义查询:

$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);

现在我卡在了年龄部分。从互联网上搜索,很高兴我从 stackoverflow 找到了代码。 get age from DOB

但不知道如何在我的自定义查询中使用它。请帮帮我。谢谢

最佳答案

您应该让 Wordpress 为您构建元查询 - 您可以使用 get_posts实现这一目标。

这里有一个建议:

$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);

您应该检查 post_type 名称是否正确,并且选择的值始终匹配“YY - YY”格式 - 如果不是,您将不得不执行一些特殊条件。

关于php - 检查我的年龄范围是否与数据库中存储的 'date of birth' 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31556106/

相关文章:

php - Nginx 重写或内部重定向循环,同时内部重定向到 "/index.html"

php - friend ,我尝试将HTML表单中的数据插入Mysql数据库,但它不起作用,也找不到错误

wordpress - 如何在自定义帖子类型永久链接中添加自定义分类法?

php - 从帖子标题集合中生成热门主题

PHP - 来自 MySQL 的基于用户登录的表

phpMyAdmin:PHP fatal error - 无法重新声明 PMA_checkLink()

php - jQuery - 单击时,选中类中的所有复选框,如果选中(执行此操作),如果没有选中(则)

MYSQL - 解析 XML 并运行查询

wordpress - 自定义帖子类型/分类 URL 结构

javascript - 帖子按年份按 Accordion 排序