【问题标题】:How to make meta_query according to dynamic meta_key values in Wordpress?如何根据 Wordpress 中的动态 meta_key 值进行 meta_query?
【发布时间】:2020-10-05 21:48:59
【问题描述】:

我正在尝试使用 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 元数据?

【问题讨论】:

    标签: wordpress meta-key meta-query


    【解决方案1】:

    根据 Fabien 的回答,我意识到我可以使用自定义 SQL 查询来解决这个问题。我创建了以下 SQL 查询:

    global $wpdb;
    $user_ids = $wpdb->get_results( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key LIKE 'course_%_access_from' AND meta_value > $first_day AND meta_value < $last_day" );,
    

    谢谢法比恩。

    【讨论】:

      【解决方案2】:

      试试这个代码:

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

      【讨论】:

      • 感谢您的回答。它没有用,但给了我一个想法。多亏了你,我突然想到我可以使用自定义 SQL 查询来做到这一点。我做到了。我将此添加为答案。有需要的可以查一下。
      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2018-02-28
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-26
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多