| 1 | <?php
|
|---|
| 2 |
|
|---|
| 3 | function wp_tax_and() {
|
|---|
| 4 | $args = func_get_args();
|
|---|
| 5 |
|
|---|
| 6 | return wp_tax_group('AND', $args);
|
|---|
| 7 | }
|
|---|
| 8 |
|
|---|
| 9 | function wp_tax_or() {
|
|---|
| 10 | $args = func_get_args();
|
|---|
| 11 |
|
|---|
| 12 | return wp_tax_group('OR', $args);
|
|---|
| 13 | }
|
|---|
| 14 |
|
|---|
| 15 | function wp_tax_group($op, $args) {
|
|---|
| 16 | return "(" . implode(" $op ", $args) . ")";
|
|---|
| 17 | }
|
|---|
| 18 |
|
|---|
| 19 | function wp_tax($taxonomy, $terms, $field = 'term_id') {
|
|---|
| 20 | return _wp_tax($taxonomy, $terms, $field, true);
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | function wp_tax_not($taxonomy, $terms, $field = 'term_id') {
|
|---|
| 24 | return _wp_tax($taxonomy, $terms, $field, false);
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | function _wp_tax($taxonomy, $terms, $field, $in) {
|
|---|
| 28 | global $wpdb;
|
|---|
| 29 |
|
|---|
| 30 | $terms = (array) $terms;
|
|---|
| 31 |
|
|---|
| 32 | switch ( $field ) {
|
|---|
| 33 | case 'term_taxonomy_id':
|
|---|
| 34 | $terms = implode( ',', array_map('intval', $terms) );
|
|---|
| 35 | break;
|
|---|
| 36 |
|
|---|
| 37 | case 'term_id':
|
|---|
| 38 | $terms = implode( ',', array_map('intval', $terms) );
|
|---|
| 39 | $terms = $wpdb->prepare("
|
|---|
| 40 | SELECT term_taxonomy_id
|
|---|
| 41 | FROM $wpdb->term_taxonomy
|
|---|
| 42 | WHERE taxonomy = %s
|
|---|
| 43 | AND term_id IN ($terms)
|
|---|
| 44 | ", $taxonomy);
|
|---|
| 45 | break;
|
|---|
| 46 |
|
|---|
| 47 | case 'slug':
|
|---|
| 48 | case 'name':
|
|---|
| 49 | $terms = "'" . implode( "','", esc_sql($terms) ) . "'";
|
|---|
| 50 | $terms = $wpdb->prepare("
|
|---|
| 51 | SELECT term_taxonomy_id
|
|---|
| 52 | FROM $wpdb->term_taxonomy
|
|---|
| 53 | INNER JOIN $wpdb->terms USING (term_id)
|
|---|
| 54 | WHERE taxonomy = %s
|
|---|
| 55 | AND $field IN ($terms)
|
|---|
| 56 | ", $taxonomy);
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | $operator = $in ? 'IN' : 'NOT IN';
|
|---|
| 60 |
|
|---|
| 61 | return "term_taxonomy_id $operator ($terms)";
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | function wp_tax_query($query) {
|
|---|
| 65 | global $wpdb;
|
|---|
| 66 | return "SELECT object_id FROM $wpdb->term_relationships WHERE " . $query;
|
|---|
| 67 | }
|
|---|
| 68 |
|
|---|
| 69 | // Example
|
|---|
| 70 | $query = wp_tax_query(wp_tax_and(
|
|---|
| 71 | wp_tax_or(
|
|---|
| 72 | wp_tax( 'post_category', 59 ),
|
|---|
| 73 | wp_tax( 'post_tag', 'web', 'slug' )
|
|---|
| 74 | ),
|
|---|
| 75 | wp_tax_not( 'post_category', 24 ),
|
|---|
| 76 | wp_tax_not( 'post_tag', 'wordpress', 'slug' )
|
|---|
| 77 | ));
|
|---|
| 78 |
|
|---|
| 79 | var_dump($query);
|
|---|
| 80 |
|
|---|