Support

Account

Home Forums Front-end Issues Query multiple meta_keys with the same value

Solved

Query multiple meta_keys with the same value

  • I would like to search multiple fields with the same value. For example: can “accounting” be found in the the following fields Services1, Services2, Services3, Services 4. And the url passing the parameter would look like this: mycompany.com/findservices?service=accounting

    Here is my current code, placing an array for the meta_key. But is not working:

    function my_pre_get_posts( $query ) {
    // do not modify queries in the admin
    if( is_admin() ) {
    return $query;
    }
    // only modify queries for ‘page’ post type
    if( isset($query->query_vars[‘post_type’]) && $query->query_vars[‘post_type’] == ‘page’ ) {
    // allow the url to alter the query
    if( isset($_GET[‘service’]) ) {
    $query->set(‘meta_key’, array(‘service1′,’service2′,’service3′,’service4’));
    $query->set(‘meta_value’, $_GET[‘service’]);
    }
    }
    // return
    return $query;
    }

  • https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

    
    $meta_query = array(
      'relation' => 'OR',
      array(
        'key' => 'service1',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service2',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service3',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service4',
        'value' => $_GET['service']
      ),
    )
    $query->set('meta_query', $args);
    
  • It didn’t work, at first.
    Then, I changed the $meta_query to $args (at the top). And it works! Thank you.

    $args = array(
      'relation' => 'OR',
      array(
        'key' => 'service1',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service2',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service3',
        'value' => $_GET['service']
      ),
      array(
        'key' => 'service4',
        'value' => $_GET['service']
      ),
    )
    $query->set('meta_query', $args);
  • Duh, my fault, name a variable one thing and then use another name, never works.

  • additional note: If you’re using meta_query array, your keys should not be prefixed with meta_. If you’re using $query->meta_key, $query->meta_value, etc. then these should still retain the prefix.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.