我有两种自定义帖子类型,播放列表和游戏。播放列表有一个 ACF 中继器字段,其中包含游戏。
我的目标:我正在尝试构建一个简单的查询,该查询获取所有没有在转发器字段中列出该游戏的播放列表以及所有为空的播放列表(根本没有任何转发器字段/数据库条目)。如果可能的话,我想使用 get_posts() 函数来实现我的目标。
我的问题:我只能通过在“game_filter”元查询比较字段中使用 = 运算符来获取查询以仅显示拥有游戏的播放列表(但我想要相反)。如果我选择 != 或 <> 或 IS NOT 运算符,它会吐出所有可用的帖子。如果我还包括我的“empty_playlists”元查询,它总是向我显示所有播放列表,无论我使用什么运算符,即使它是 OR 并且列出的帖子确实有条目。
我尝试了很多,但无法让它工作。我发现的所有示例都是关于不同的事情,主要是关于中继器字段名称及其解决方案的 % 问题。我希望有人能快速帮助我。我究竟做错了什么?请帮助其他更好的编码人员!:-)
这是我的代码
$excluded_playlists_game_id = 274;
$user_id = 1;
$args = array(
'post_type' => PSiCorePostTypes::PLAYLISTS,
'author' => $user_id,
'order_by' => 'title',
'order' => 'ASC',
'suppress_filters' => false,
'meta_query' => array(
'relation' => 'OR',
'game_filter' => array(
'type' => 'NUMERIC',
'key' => 'psi_playlist_games_%_item',
'compare' => '!=',
'value' => $excluded_playlists_game_id,
),
'empty_playlists' => array(
'key' => 'psi_playlist_games_%_item',
'compare' => 'NOT EXISTS',
),
),
);
$user_playlists = get_posts( $args );
这个函数用于 % 问题。
add_filter( 'posts_where', 'get_user_playlists_query_allow_wildcard' );
function get_user_playlists_query_allow_wildcard( $where ) {
global $wpdb;
$where = str_replace(
"meta_key = 'psi_playlist_games_%_item",
"meta_key LIKE 'psi_playlist_games_%_item",
$wpdb->remove_placeholder_escape( $where )
);
return $where;
}