是否可以在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"
Run Code Online (Sandbox Code Playgroud)
这给了我想要的结果.
然后我尝试使用WordPress中的内置get_posts()函数来做到这一点:
get_posts(array('meta_key' => 'additional_downloads%', 'meta_value' => 81))
Run Code Online (Sandbox Code Playgroud)
但这给了我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 );
Run Code Online (Sandbox Code Playgroud)
$args = [
'suppress_filters' => false,
'wildcard_on_key' => true,
'meta_query' = [
[
'key' => 'additional_downloads_%',
'value' => 81
]
]
];
$q = get_posts( $args );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
716 次 |
| 最近记录: |