WP Query by variable custom field

Directly using WP_Query, I don’t think this is possible as you would require some logic inside the WP_Query which allowed you to say ‘if primary_geo is set to NJ then look in NJ, or if it’s set to PA then look in PA’.

However, what you could do is use a hook to update a new single meta value on that post which stores the ‘effective’ geo field – i.e. the value for whichever location the ‘primary_geo’ is pointing at. You can achieve that with something like this:

add_action('save_post', 'update_geo_value', 10, 2);

function update_geo_value($postID, $post) {
   $primaryGeo = get_post_meta($postID, 'primary_geo');

   if ($primaryGeo == 'NJ') {
       $georesult = get_post_meta($postID, 'nj_field');
   } elseif ($primaryGeo == 'PA') {
       $georesult = get_post_meta($postID, 'pa_field');
   } else { 
       echo "This should probably never happen. Put some debug logging here!";
   }

   update_post_meta($postId, 'effective_geo_value', $georesult);

}

Note this is example code and may need correction / changing values or code according to your use variables, etc.

So what this does is move that logic about figuring out which field to use to the point when a post is saved, and then the value ‘effective_geo_value’ is the one you need which corresponds to either NJ or PA. You can then obviously use effective_geo_value in a WP_Query with the post meta parameters

Note:

  • You’d need to update this calculated value every time you update any of the involved meta values for this post! I.e. if the item moved from NJ to PA for some reason, you’d need to update the effective_geo_value.

HTH