Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I suggest building a custom SQL query to pass to <code>$wpdb</code>, since complex taxonomy queries are notoriously harder to implement than their SQL equivalents.</p> <p><strong>Note</strong>: You can always <a href="http://codex.wordpress.org/Editing_wp-config.php#Save_queries_for_analysis" rel="nofollow">output the most recent SQL WordPress executed</a>. This is a very nice way to debug these kind of problems.</p> <p>Back to your question, this is what the final code snippet would look like:</p> <pre><code>$gender = 'unknown'; $taxonomy = array('male' =&gt; 'mens', 'female' =&gt; 'womens'); $where_clause = ''; if ( array_key_exists($gender, $taxonomy) ) { $where_clause = sprintf("WHERE %s = '%s'", "$wpdb-&gt;terms.slug", $taxonomy[$gender]); } $query = "SELECT $wpdb-&gt;posts.* FROM $wpdb-&gt;posts INNER JOIN $wpdb-&gt;term_relationships ON ($wpdb-&gt;posts.ID = $wpdb-&gt;term_relationships.object_id) INNER JOIN $wpdb-&gt;term_taxonomy ON ($wpdb-&gt;term_relationships.term_taxonomy_id = $wpdb-&gt;term_taxonomy.term_taxonomy_id) INNER JOIN $wpdb-&gt;terms ON ($wpdb-&gt;term_taxonomy.term_id = $wpdb-&gt;terms.term_id) $where_clause"; $posts = $wpdb-&gt;get_results($query); </code></pre> <p><strong>Update</strong>:</p> <p>If you prefer to use tax_query:</p> <pre><code>$gender = 'unknown'; // Build Gender Tax-Query if($gender == 'male') { $gender_query = array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; 'mens', 'operator' =&gt; 'IN' ) ); } elseif($gender == 'female') { $gender_query = array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; 'womens', 'operator' =&gt; 'IN' ) ); } else { $gender_query = array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; array('mens', 'womens'), 'operator' =&gt; 'IN' ) ); } // Get posts $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 2, 'orderby' =&gt; 'rand', 'tax_query' =&gt; $gender_query ); $posts = get_posts($args); </code></pre> <p>The key to both answers is that you should not <em>exclude</em> items based on gender, but rather include (assuming the gender neutral items are properly categorized in <em>womens</em> and <em>mens</em>).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload