Support

Account

Home Forums General Issues Query posts where relationship field value is inside an array

Solved

Query posts where relationship field value is inside an array

  • Dear community,
    I am struggling with filtering my custom posts by relationship field. Field returns ID of related post and there could be only one related post. So basically my field looks like that:

    Array
    (
        [0] => 319
    )

    Let say that I have an array with IDs [317, 319] and I want to query my custom posts and use meta query to find all of the posts that have relationship field value equal to any ID from array above.
    I know that relationship field stores values as arrays. So far I end up with this piece of code and I am running out of ideas. I have done some research but I found none of the helpfull.

    if (isset($_POST['region'])) {
            $regions_arr = $_POST['region'];
            foreach ($regions_arr as $id) {
                $region_relations[] = array(
                    'key' => 'product-region',
                    'value' => $id,
                    'compare' => 'LIKE'
                );
            }
            $args['meta_query'][] = array(
                'relation' => 'OR',
                array_merge(array('relation' => 'OR'), $regions_relations)
            );
     }

    I would really appreciate any tips and help from you.

  • 
    if (isset($_POST['region'])) {
      $regions_arr = $_POST['region'];
      $meta_query = array('relation' => 'OR');
      foreach ($regions_arr as $id) {
        $meta_query[] = array(
          'key' => 'product-region',
          'value' => '"'.$id.'"',
          'compare' => 'LIKE'
        );
      }
      $args['meta_query'] = $meta_query;
    }
    
  • Thank you, but it doesn’t work like i need. Code below works like a charm for me:

    if (isset($_POST['regions'])) {
            $regions_arr = $_POST['regions']; // [319, 315]
            foreach ($regions_arr as $id) {
                $region_relations[] = array(
                    'key' => 'product-region',
                    'value' => "$id",
                    'compare' => 'LIKE'
                );
            }
    
            $args['meta_query'][] = array(
                array_merge(array('relation' => 'AND'), $region_relations)
            );
        }
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.