具有2个相等元的用户的Wordpress查询

时间:2016-09-06 19:05:44

标签: php mysql wordpress wordpress-theming

如何让所有拥有2个自定义元字段meta_1meta_2的用户具有相同的价值?

例如:

// This user will be in the result
User 1:
meta_key : meta_1, meta_value: 6
meta_key : meta_2, meta_value: 6

// This user will also be in the result
User 2:
meta_key : meta_1, meta_value: 9001
meta_key : meta_2, meta_value: 9001

// This user will NOT be in the result
User 3:
meta_key : meta_1, meta_value: 25
meta_key : meta_2, meta_value: 6

// This user will NOT be in the result
User 4:
meta_key : meta_1, meta_value: 9001
// (this user does not have meta_2)

1 个答案:

答案 0 :(得分:1)

我这样做的方式:

WP_Query 添加额外的参数:

$args = array(
'equal_meta' => array('meta_1', 'meta_2')
);
$query = new WP_Query( $query_args );

并为其创建join filter

function my_posts_join( $join, $query ) {

    if( _some_security_checks_if_needed ) {
       $rule = $query->get('equal_meta', array());
       if(!empty($rule) {
           ... write custom INNER JOIN using data from $rule
           $join .= $customJoin
       }
    }
    return $join;
} 

我认为加入是最好的方式,但可能会更好......我不是SQL大师;)

当然' bind'过滤器:

add_filter('posts_join', 'my_posts_join');
$query = new WP_Query( $query_args );
remove_filter('posts_join', 'my_posts_join');

如果您希望将此过滤器应用于每个 WP_Query 而不是特定的过滤器,那么您应该'绑定'它在函数之外的某个地方,最好的做法是在它调用的函数之前/之后添加它:

add_filter('posts_join', 'my_posts_join');
function my_posts_join( $join, $query ) { ... }

然后你不必将其删除。

[ADDED SQL]

我能想到的最简单的SQL查询:

select wu.* from wp_users wu
-- two joins ensure we get only users with existing both meta values
inner join wp_usermeta wm1 on wm1.user_id = wu.ID and wm1.meta_key = 'meta_1'
inner join wp_usermeta wm2 on wm2.user_id = wu.ID and wm2.meta_key = 'meta_2'
-- now we filter only those with the same meta
where wm1.meta_value = wm2.meta_value;

这表明我们需要两个过滤器:posts_join和posts_where。我希望你能根据我的答案设法创建它们。

$ customJoin应该看起来像这样(伪代码):

inner join wp_usermeta wm1 on wm1.user_id = wu.ID and wm1.meta_key = $rule[0]
inner join wp_usermeta wm2 on wm2.user_id = wu.ID and wm2.meta_key = $rule[1]

$ customWhere:

AND wm1.meta_value = wm2.meta_value

请注意,在哪里有AND,因为$ where(函数的第一个参数)实际上会包含开头。

您还应该在自定义查询字符串的开头添加一个空格,否则它们可能会生成无效的SQL。