WordPress中如何将下拉字段的关联逻辑从AND替换为OR?代码调试求助
Hey there! Let's get that city dropdown working with OR logic like your region field. Looking at your code, the issue comes down to how you're structuring the tax_query for cities—your current setup is creating a messy nested structure that WordPress can't parse correctly.
Here's the Problem with Your Current Code
In your foreach loop for cities, you're adding a new 'relation' => 'OR' every time you loop through a city value. This breaks the tax query structure because WordPress expects relation rules to sit at the same level as the conditions they apply to, not nested inside each individual condition.
The Fixed Code
Let's restructure the city tax query to group all city conditions under a single OR relation:
function filter_florida_location() { ob_start(); // Main relation stays AND (Region AND City conditions must both be satisfied; change to OR if you want either/or) $tax_query = array('relation' => 'AND'); // Region logic (enable IN operator for OR matching) if (isset($_POST['region']) && !empty($_POST['region'])) { $tax_query[] = array( 'taxonomy' => 'region', 'field' => 'term_id', 'terms' => $_POST['region'], 'operator' => 'IN', // IN = OR logic for multiple region selections ); } // City logic with proper OR grouping if (isset($_POST['city']) && !empty($_POST['city'])) { // Create a sub-query for cities with OR relation $city_conditions = array('relation' => 'OR'); foreach($_POST['city'] as $val){ $city_conditions[] = array( 'taxonomy' => 'city', 'field' => 'term_id', 'terms' => array($val), ); } // Add the city sub-query to the main tax query $tax_query[] = $city_conditions; } // Make sure to use the tax_query in your WP_Query (example below) $args = array( 'post_type' => 'your_post_type', // Replace with your actual post type 'tax_query' => $tax_query, // Add any other query args you need ); $location_query = new WP_Query($args); // Output your query results here... ob_end_flush(); }
Key Changes Explained
- City Sub-Query: We create a separate
$city_conditionsarray with'relation' => 'OR'—this tells WordPress to match any of the selected city terms. - Cleaner Structure: All city conditions are added to this sub-query, which is then added to the main
$tax_queryas a single item. This keeps the tax query structure valid. - Region OR Logic: I uncommented
'operator' => 'IN'for the region field—this makes multiple region selections use OR logic too, matching what you want for cities.
Quick Checks
- Ensure your city dropdown has a name attribute like
city[](the square brackets are critical for sending multiple selections as an array via POST). - Double-check that your
WP_Queryis actually using the$tax_querywe built (I added an example of this in the code).
That should do it—your city selections will now use OR logic just like the region field!
内容的提问来源于stack exchange,提问作者thunder_rsa

