Creating a Search Array From Multiple Tables

I’m working with a client’s WordPress site that has user submissions (via TDO Mini Forms) from multiple countries, and they would like to be able to search for posts by region – Europe, Africa, Central America, etc.

There is a custom field already in place for the user’s country of origin. I also have a separate table that maps countries to regions. What I want to do is make it so that the user can select Europe, for example, from a map, and have WP return any posts from countries that are mapped as EU.

Read More

What’s the best way to accomplish this? Not only do I not want to reinvent the wheel, but WP can be very fussy about it search functions.

My first thought was to perform a search of the Regions table, return all of the countries as an array, and then use that array to perform a WP search, but I’m not finding how to do that without creating an AND search, which returns nothing.

Thanks for any help.

ty

Related posts

Leave a Reply

1 comment

  1. You’ve got the right idea. If you get an array of country IDs within a region, you can pass that array to a meta query IN comparison:

    $country_ids = array(1,2,3); // this would be the result from fetching countries associated with a region.
    $args = array(
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => 'country',
                'value' => $country_ids,
                'compare' => 'IN'
            )
        )
    );
    $query = new WP_Query( $args );
    

    EDIT- this is assuming the ID is stored, if you’re storing the country names as the value, you should query with an array of the names.