Search code examples
wordpresscustom-post-typecustom-fields

Get all Posts If has same custom field values in Posts


Trying to get all the posts having the same zipcode as metavalue. Thanks in advance for the help.

<?php
                 $query = new WP_Query( array(
                         'post_type'=> array('service'),
                         'posts_per_page' => -1,
                         'meta_query' => array( array(
                              'key'=> 'zipcode',
                              'value'=> ','.$zip.',',
                              'compare'=> 'LIKE'
                             ) )
                         ));                 
?>      

    <?php if ( $query->have_posts() ) :while ( $query->have_posts() ) : $query->the_post();  ?>
           <h3><?php the_title(); ?></h3>
    <?php endwhile; // end of the loop. ?>
    <?php wp_reset_query(); ?>
    <?php else: ?>
          No results found.
    <?php endif; ?>

zipcode are numbers for example 12345. If posts have value 12345 in the custom field. then it should display all posts which have the 12345 value. The above code is working fine but displays only one post.


Solution

  • Following code will be the proper for the meta query.

      $query_args = array(
            'post_type'   => 'service',
            'posts_per_page' => -1,
            'meta_query'  => array(
                array(
                    'value'   => $zip,
                    'compare' => 'LIKE',
                    'key'     => 'zipcode',
                ),
            )
        );
       $query = new WP_Query($query_args);
       <?php if ( $query->have_posts() ) :while ( $query->have_posts() ) : $query->the_post();  ?>
           <h3><?php the_title(); ?></h3>
       <?php endwhile; // end of the loop. ?>
       <?php wp_reset_query(); ?>
       <?php else: ?>
          No results found.
       <?php endif; ?>
    

    Hope it helps.