wp query - How to set meta_query if get_post_meta returns nested array for that key?

admin2025-06-04  2

This question already has answers here: How can I create a meta_query with an array as meta_field? (5 answers) Closed 6 years ago.

I need to get posts with specific post meta. If I inspect regular loop using following code:

$args = array(
    'post_status' => 'published',
    'posts_per_page' => 77,
    'post_type' => 'post',
);
$query = new WP_Query($args);
while ($query->have_posts()) : $query->the_post(); 

$literature = get_post_meta(get_the_ID(), 'popis_literature'); 
var_dump($literature);

endwhile; 

for some posts var_dump gives an array of data like this

array (size=1)
  0 => 
    array (size=2)
      0 => string '32985' (length=5)
      1 => string '59956' (length=5)

How can I query posts by one of those IDs? This doesn't give me anything

$args = array(
    'post_status' => 'published',
    'posts_per_page' => -1,
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'popis_literature',
            'value'   => array('32985'),
            'compare' => 'IN'
        )
    ),
);
This question already has answers here: How can I create a meta_query with an array as meta_field? (5 answers) Closed 6 years ago.

I need to get posts with specific post meta. If I inspect regular loop using following code:

$args = array(
    'post_status' => 'published',
    'posts_per_page' => 77,
    'post_type' => 'post',
);
$query = new WP_Query($args);
while ($query->have_posts()) : $query->the_post(); 

$literature = get_post_meta(get_the_ID(), 'popis_literature'); 
var_dump($literature);

endwhile; 

for some posts var_dump gives an array of data like this

array (size=1)
  0 => 
    array (size=2)
      0 => string '32985' (length=5)
      1 => string '59956' (length=5)

How can I query posts by one of those IDs? This doesn't give me anything

$args = array(
    'post_status' => 'published',
    'posts_per_page' => -1,
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'popis_literature',
            'value'   => array('32985'),
            'compare' => 'IN'
        )
    ),
);
Share Improve this question asked Jan 27, 2019 at 1:32 Ivan TopićIvan Topić 5211 gold badge6 silver badges20 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

You have miss the last parameter from get_post_meta().

Try below code:

$literature = get_post_meta(get_the_ID(), 'popis_literature', true);

It gives you array of IDs. E.g.

array (size=2) 0 => string '32985' (length=5) 1 => string '59956' (length=5)

So in query you can use them like:

$args = array( 'post_status' => 'published', 'posts_per_page' => -1, 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'popis_literature', 'value' => $literature, 'compare' => 'IN' ) ), );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748971655a315272.html

最新回复(0)