使用get_post_meta数组作为meta_query值

时间:2016-06-22 13:33:21

标签: php mysql wordpress

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

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

获取元数据

$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

如何修改我的脚本以处理post meta,以便查询每个GUID?

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

发布BY523643

DC242003的2篇帖子

1 个答案:

答案 0 :(得分:0)

您可以使用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都是唯一的,并且您可能不会遇到相同数量的字符。