Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress meta_query LIKE compare values from an array

I have a script that looks like this:

  foreach($target_zips as $zipcode) {

      $query_adresses = array (
        'order'     => 'ASC',
        'cat'       => $_GET["cat"],
        'post_type'=> 'adressen',
        'posts_per_page'   => '-1',
        'meta_query' => array(
            array(
                'key'     => 'postcode',
                'value'   => $zipcode,
                'compare' => 'LIKE',
            )
        )
      );

      $results = get_posts( $query_adresses );

      $matched_adresses[] = $results;

  }

A script that goes through an array of values, then queries a lot of posts to see if there's posts that match meta_query. This is terribly slow. Is it possible to put an array of values in this meta_query instead of querying over and over again for each value in $target_zips?


1 Answers

You can run just one get_posts() query that will return all the results. Build the meta_query beforehand.

$meta_query = [];


/**
 * This will return all posts that contain at least one meta_query from the loop
 */
$meta_query['relation'] = 'OR';


foreach ( $target_zips as $zipcode ) {
    $meta_query[] = [
        'key'     => 'postcode',
        'value'   => $zipcode,
        'compare' => 'LIKE',
    ];
}


$query_adresses   = [
    'order'          => 'ASC',
    'cat'            => $_GET["cat"],
    'post_type'      => 'adressen',
    'posts_per_page' => '-1',
    'meta_query'     => $meta_query
];
$matched_adresses = get_posts( $query_adresses );

See this for for more details: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

like image 96
C. Smith Avatar answered Jul 24 '26 23:07

C. Smith