在包含逗号分隔列表的元字段内查找字符串的META_Query

时间:2021-06-11 作者:Nicolai

在我的项目中,WP用户有一个自定义的元字段;“用户组”;包含以逗号分隔的值列表。元字段可以包含如下值:

WS,CT,IS,TS,TS-IS,TS-WS,TS-CT
现在,我想创建一个meta\\u query(),它返回所有具有值的用户,例如;IS“是”;在这个领域。我可以通过以下代码实现这一点:

    $args = array(
        \'meta_query\' => array(
            array(
                \'key\' => \'usergroup\',
                \'value\' => \'IS\'
                \'compare\'   => \'IN\'
            )
        )
    );
    $users = get_users($args);
但比较=>;在所有出现的匹配中;是“;,“也是这样”;TS-IS“;,这是不需要的。

是否有一种聪明的方法来实现meta\\u查询,使其只与“匹配”;是,但不是;TS-IS“是吗?”;?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

Is there a smart way to meta_query so it matches just "IS, but not "TS-IS"?

The WordPress meta query class (WP_Meta_Query), which among others, is used with the posts (WP_Query) and users (WP_User_Query) query classes, supports REGEXP (since WordPress 3.7) as the compare value, so you could use that with a RegEx (regular expresion) pattern like (^|,)IS(,|$), like so:

\'meta_query\' => array(
    array(
        \'key\'     => \'usergroup\',
        \'compare\' => \'REGEXP\',
        // With dynamic values, be sure to properly escape the "IS" or whatever
        // is the actual value. E.g. \'(^|,)\' . preg_quote( $value ) . \'(,|$)\'
        \'value\'   => \'(^|,)IS(,|$)\',
    ),
),

So that should work well for meta values that in the database are stored in the form of a comma-separated list, i.e. value, value, value, ... (with or without the whitespaces), and you can test the above pattern here.

However, since you said (in the comments) that the meta values are actually serialized like so:

a:11:{i:0;s:2:"IS";i:1;s:5:"TS-IS";i:2;s:6:"TS-USA";i:3;s:2:"TS";i:4;s:3:"EKG";i:5;s:2:"WS";i:6;s:2:"CT";i:7;s:6:"TS-MAX";i:8;s:5:"TS-XD";i:9;s:6:"TS-CTM";i:10;s:5:"TS-MT";}

Then you would instead want to use LIKE as the compare value, but use "<value>" as the value\'s value like this:

\'meta_query\' => array(
    array(
        \'key\'     => \'usergroup\',
        \'compare\' => \'LIKE\',
        // With dynamic values, be sure to properly escape the "IS" or whatever
        // is the actual value.
        \'value\'   => \'"IS"\',
    ),
),

Try a demo on DB Fiddle.

相关推荐

如何让`wp-list-table`显示我在Custom-Post中的`Custom-Fields`

一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: