Search code examples
wordpresscmb2

Wp query by postmeta in array field [0]


I'm trying to query a post type by meta value, but the value is [0] field in array.

$args = array('post_type'=>'event','meta_query' => array(
    array(
        'key' => 'my_post_multicheckbox', 
         // The right value should be my_post_multicheckbox[0] 
         // and it's serialized
        'value' => serialize($current_post_ID)
    )
));
$events = new WP_Query($args);
while ($events->have_posts()):$events->the_post(); 
the_title();
endwhile;
wp_reset_query();

Obviously it does not show any post, any idea?


Solution

  • When you store multiple selected value as meta value, its value are being store in serialise form like

    a:2:{i:0;s:2:"53";i:1;s:2:"54";} // where 53 and 54 are 2 selected ids.
    

    Now, if you want to get post which has selected id = 53, then you need to pass "compare" parameter in your meta query with "Like". By default it will compare with "=" condition.

    So your Wp_query should be as follow:

    $args = array('post_type'=>'event','meta_query' => array(
        array(
            'key' => 'my_post_multicheckbox', 
             // The right value should be my_post_multicheckbox[0] 
             // and it's serialized
            'value' => $current_post_ID, // this should not be serialise value.
            'type' => 'CHAR',
            'compare' => 'LIKE',
        )
    ));
    $events = new WP_Query($args);
    

    If you want to fetch post by multiple Id, instead of 'Like', you need to pass 'IN' and in value, you need to pass array of ids by which you want to get the posts.