I'm trying to print posts if any posts have custom field value X. My code is working correctly but this is not working if the custom field has multiple values X, Y, Z. Location is a CF Meta and X is value. And at here [get_post_meta(get_the_ID(), 'Location', true)));] Location Meta is also inserted on a page where I want to output and on that page there are also have CF value X. If the post's values are X, Y, Z then the code fails to print posts. Sorry for lacking skills of explanation here.

    $posts = get_posts(array(
    'numberposts' => 10,
    'post_type' => 'post',
    'post_status' => 'publish',
    'orderby' => 'date',
    'meta_key' => 'Location',
    'meta_value' => get_post_meta(get_the_ID(), 'Location',true)));
    if($posts) {
        foreach($posts as $post) {
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
         <?php wp_reset_query(); ?>
  • wp_reset_query should only be used after a call to query_posts. Is there a reason you used get_posts instead of WP_Query? Functions such as the_title require that the current post be set, which a get_posts loop doesn't do automatically and isn't present in the questions code
    – Tom J Nowell
    Jun 23, 2021 at 15:48

1 Answer 1


You could use meta_query, it can handle arrays and strings.

So something like this

// get location meta, will be easier to determine what is the type of value
$location = get_post_meta(get_the_ID(), 'Location',true);

$posts = get_posts([
    'posts_per_page' => 10,
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'orderby'        => 'date',
    'meta_query'     => [
            'key'     => 'Location',
            'value'   => $location,
            'compare' => is_array($location) ? 'IN' : '='

Now you can do all the rest as usual.

So what we did here is

  1. get and assing Location meta to a variable, $location
  2. add that variable as value in the meta_query
  3. based on the type of value of the variable we create the compare logic

By the way, get_permalink() and the_title() will output/return the link and title of the current post, NOT the looped post.

When using get_posts() they are available as object properties, so like this

foreach($posts as $post) {
    $post->post_title; // the post title
    get_permalink($post->ID) // the looped post permalink, we need to pass the looped post ID as argument to "tell" get_permalink what link we need
  • Note that the final code block will not trigger filters the way the_title does, you should instead setup postdata so that the current post is set, then sue the appropriate cleanup function afterwards
    – Tom J Nowell
    Jun 23, 2021 at 15:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.