user2568495
user2568495

Reputation:

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?

Upvotes: 3

Views: 15365

Answers (2)

Jesus Carrillo
Jesus Carrillo

Reputation: 21

C. Smiths solution is correct but there is a simpler solution.

You can utilize the IN clause in your compare key. Set the value key to an array of values that need to be compared.

More info and examples can be found here. https://developer.wordpress.org/reference/classes/wp_meta_query/#accepted-arguments

Edit

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

Note

Like sMyles suggested, you MUST validate/sanitize your external data ($_GET)

Upvotes: 0

C. Smith
C. Smith

Reputation: 101

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

Upvotes: 2

Related Questions