gpt4 book ai didi

php - 使用 get_post_meta 数组作为 meta_query 值

转载 作者:行者123 更新时间:2023-11-29 20:51:56 25 4
gpt4 key购买 nike

我正在尝试查询数据库中的元数据_players,该数据库已将序列化数组作为值,数据通过 WordPress 元框插入。

我以为我可以对 get_post_meta 的序列化版本进行 LIKE 比较,但结果仅显示具有确切序列化字符串的帖子。

获取元数据

$keyGUID = serialize(get_post_meta($postID, "_players", true));
// returns "a:2:{i:0;s:8:"DC242003";i:1;s:8:"BY523643";}"

构建查询争论

$types = get_post_types();
$args = array(
"post_type" => $types,
"post_status" => "publish",
"posts_per_page" => $posts,
"meta_query" => array(
array(
"key" => "_players",
"value" => $keyGUID,
"compare" => "LIKE"
)
)
);
$myposts = get_posts($args);

以及我正在查询的数据库记录

enter image description here

如何修改我的脚本来处理帖子元,以便它查询每个 GUID?

我想要发生的是,如果其中一个值存在,则显示帖子,如果它们都存在,则显示帖子

1 个帖子 BY523643

DC242003 的 2 个帖子

最佳答案

您可以使用 LIKE 查询序列化字符串,但需要分解 ID 并使用这些 ID 作为参数进行搜索。

$players = get_post_meta( $postID, "_players", true );

// to get any posts that have either player
$types = get_post_types();
$args = array(
"post_type" => $types,
"post_status" => "publish",
"posts_per_page" => $posts,
"meta_query" => array(
'relation' => 'OR',
)
);

foreach ( $players as $player_id ) {
$args['meta_query'][] = array(
"key" => "_players",
"value" => $player_id,
"compare" => "LIKE"
);
}


$myposts = get_posts( $args );

// to get posts per player
foreach ( $players as $player_id ) {
$args = array(
"post_type" => $types,
"post_status" => "publish",
"posts_per_page" => $posts,
"meta_query" => array(
array(
"key" => "_players",
"value" => $player_id,
"compare" => "LIKE"
)
)
);

$myposts = get_posts( $args );

// do something with the posts for this player
}

在序列化字符串上使用 LIKE 的缺点之一是有时会得到不需要的结果。例如,您有一个 ID 为 12345 的玩家和 ID 为 123 的玩家。如果您搜索 123,您将找到两个玩家。但如果您的所有 ID 都是唯一的并且字符数相同,您可能不会遇到该问题。

关于php - 使用 get_post_meta 数组作为 meta_query 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37969682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com