wordpress - 如何根据 Wordpress 中的动态 meta_key 值进行 meta_query?
问题描述
我正在尝试使用 get_users 函数列出一些用户。
我使用的在线学习插件将用户元数据中的一些数据保存为 course_COURSEID_access_from。例如; 如果课程 ID 为 123,则元数据保存为:course_123_access_from。这个元数据的值是一个时间戳。例如; 1600724678。
// First day of the month.
$first_day = strtotime( date( 'Y-m-01' ) );
// Last day of the month.
$last_day = strtotime( date( 'Y-m-t' ) );
$args = array(
'fields' => 'ID',
'role' => 'customer',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'course_%_access_from',
'value' => array( $first_day, $last_day ),
'type' => 'numeric',
'compare' => 'BETWEEN'
),
)
);
$users = get_users($args);
但我无法得到任何结果。我在哪里犯错?
如何根据动态 meta_keys 查询 wordpress 元数据?
解决方案
试试这个代码:
<?php
function filter_request_sql_where($where)
{
if (strpos($where, "meta_key = 'course_$_access_from")) {
$where = str_replace("meta_key = 'course_$_access_from", "meta_key LIKE 'course_%_access_from", $where);
}
return $where;
}
add_filter('posts_where', 'filter_request_sql_where');
// First day of the month.
$first_day = strtotime(date('Y-m-01'));
// Last day of the month.
$last_day = strtotime(date('Y-m-t'));
$args = array(
'fields' => 'ID',
'role' => 'customer',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'course_$_access_from',
'value' => array($first_day, $last_day),
'type' => 'numeric',
'compare' => 'BETWEEN'
),
)
);
$users = get_users($args);
推荐阅读
- parameters - 水晶报表参数中的某些值没有出现
- prolog - 相同结构的 WAM 寄存器分配
- python - Pandas 数据框中的二值化列
- python - TypeError:从字符串中删除最后 3 个字符时,'float' 对象不可下标
- r - R 新手,需要计算我运行 while 循环的时间
- c# - 重定向后单击链接时页面 URL 重复
- reactjs - 与使用可变数据结构相比,为什么插入不可变的 trie 只会慢一个常数时间?
- php - (php,laravel)如何通过foreach循环从分组数组中插入多张图片到数据库中
- mysql - 对于 MYSQL 5.7.31 - 应该为传输连接更改哪个超时变量:连接超时
- python - 如何在 python 中使用枚举来增加行位置