WordPress在get_posts中使用通配符


WordPress use wildcard in get_posts

是否可以在 get_posts() 函数中使用通配符?

我已经在SQL中进行了我想要的查询:

select * from wp_posts p
left join wp_postmeta pm on p.id = pm.post_id
where pm.meta_key like 'additional_downloads%' and pm.meta_value = 81 and p.post_status = "publish"

这给了我想要的结果。

然后我尝试使用WordPress中内置的get_posts()函数来做到这一点:

get_posts(array('meta_key' => 'additional_downloads%', 'meta_value' => 81))

但这给了我 0 个结果。我需要这个通配符的原因是,一个帖子可以有 1 个以上的额外下载,并且这些下载存储在wp_postmeta表中,meta_keys additional_downloads_0"、"additional_downloads_1"等

知道如何使用wordpress函数执行此操作吗?

我们可以过滤查询的 WHERE 子句。

过滤器

add_filter( 'posts_where', function ( $where, 'WP_Query $q )
{ 
    // Check for our custom query var
    if ( true !== $q->get( 'wildcard_on_key' ) )
        return $where;
    // Lets filter the clause
    $where = str_replace( 'meta_key =', 'meta_key LIKE', $where );
    return $where;
}, 10, 2 );

查询

$args = [
    'suppress_filters' => false,
    'wildcard_on_key' => true,
    'meta_query' = [
        [
            'key' => 'additional_downloads_%',
            'value' => 81
        ]
    ]
];
$q = get_posts( $args );