0

I am trying to filter the contents of a WP Query using a meta_query. I have a feeling it's to do with the saved value being a serialised array but I've tried a few fixes online to no avail. Should have all the info you need below in code comments.

    $user_id = get_current_user_id();
    var_dump($user_id); //int(1)

    $assignedZones = get_field('author_assigned_zones', 'user_'.$user_id);
    var_dump($assignedZones); //array(1) { [0]=> object(WP_Term)#17784 (10) { ["term_id"]=> int(9) ["name"]=> string(6) "Zone 2" ["slug"]=> string(6) "zone-2" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(9) ["taxonomy"]=> string(5) "zones" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(0) ["filter"]=> string(3) "raw" } }

    $zoneIDs = array();
    var_dump($zoneIDs); //array(0) { }

    foreach ($assignedZones as $assignedZone ) {
        $zoneIDs[] = $assignedZone->term_id;
    } var_dump($zoneIDs); //array(1) { [0]=> int(9) }

    $hostQuery = new WP_Query(array(
        'post_type' => 'hosts',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => 'host_zones',//DB Value = a:3:{i:0;s:1:"9";i:1;s:2:"12";i:2;s:2:"13";}
                'value' => $zoneIDs, //array(1) { [0]=> int(9) }
                'compare' => 'IN'
            )
        )
    ));
Daniel Vickers
  • 1,054
  • 1
  • 12
  • 32
  • I guess you could `'value' => serialize(json_encode($zoneIDs)) ), 'compare' => 'LIKE',` - This way, your query is looking for the following `s:1:"9"` - The json_encode is needed, since else it would lool for `i:9` Which is clearly not the same. – Stender May 19 '21 at 12:37
  • Here’s a [post over at ACF](https://support.advancedcustomfields.com/forums/topic/meta-query-array-over-serialized-values/). Basically, the recommend performing an `OR` query with multiple quoted LIKE queries – Chris Haas May 19 '21 at 12:39
  • my comment probably only works, if there is only ONE id in `$zoneIDs`... so probably useless for you :-D – Stender May 19 '21 at 12:39
  • But the snippet from ACF with multiple `or`s could be done with a foreach output and array_merge on your $zoneIds – Stender May 19 '21 at 12:41
  • Any ideas how to do the foreach as I tried that first using an answer on Stackoverflow that had no success unfortunately. – Daniel Vickers May 19 '21 at 12:51

0 Answers0