1 | <?php |
---|
2 | |
---|
3 | class WP_Tax_Group extends WP_Tax_Query { |
---|
4 | |
---|
5 | function __construct($operator, $args) { |
---|
6 | $this->operator = $operator; |
---|
7 | $this->args = $args; |
---|
8 | } |
---|
9 | |
---|
10 | function get_sql() { |
---|
11 | $args = $this->traverse($this->args); |
---|
12 | |
---|
13 | return "(" . implode(" $this->operator ", $args) . ")"; |
---|
14 | } |
---|
15 | |
---|
16 | function traverse($arg) { |
---|
17 | if ( is_array($arg) ) |
---|
18 | return array_map(array($this, 'traverse'), $this->args); |
---|
19 | |
---|
20 | if ( is_a($arg, 'WP_Tax_Query') ) |
---|
21 | return $arg->get_sql(); |
---|
22 | |
---|
23 | return $arg; |
---|
24 | } |
---|
25 | } |
---|
26 | |
---|
27 | class WP_Tax_Item extends WP_Tax_Query { |
---|
28 | function __construct($taxonomy, $term_ids, $not = false) { |
---|
29 | $this->taxonomy = $taxonomy; |
---|
30 | $this->term_ids = $term_ids; |
---|
31 | $this->not = $not; |
---|
32 | } |
---|
33 | |
---|
34 | function get_sql() { |
---|
35 | return _wp_tax($this->taxonomy, $this->term_ids, $this->not); |
---|
36 | } |
---|
37 | } |
---|
38 | |
---|
39 | class WP_Tax_Query { |
---|
40 | function get_sql() { |
---|
41 | return ''; |
---|
42 | } |
---|
43 | } |
---|
44 | |
---|
45 | |
---|
46 | function wp_tax_and() { |
---|
47 | $args = func_get_args(); |
---|
48 | |
---|
49 | return new WP_Tax_Group('AND', $args); |
---|
50 | } |
---|
51 | |
---|
52 | function wp_tax_or() { |
---|
53 | $args = func_get_args(); |
---|
54 | |
---|
55 | return new WP_Tax_Group('OR', $args); |
---|
56 | } |
---|
57 | |
---|
58 | |
---|
59 | function wp_tax($taxonomy, $term_ids) { |
---|
60 | return new WP_Tax_Item($taxonomy, $term_ids); |
---|
61 | } |
---|
62 | |
---|
63 | function wp_tax_not($taxonomy, $term_ids) { |
---|
64 | return new WP_Tax_Item($taxonomy, $term_ids, true); |
---|
65 | } |
---|
66 | |
---|
67 | function _wp_tax($taxonomy, $term_ids, $not = false) { |
---|
68 | global $wpdb; |
---|
69 | |
---|
70 | $term_ids = implode(',', array_map('intval', (array) $term_ids)); |
---|
71 | |
---|
72 | $operator = $not ? 'NOT IN' : 'IN'; |
---|
73 | |
---|
74 | return $wpdb->prepare("( |
---|
75 | SELECT object_id |
---|
76 | FROM $wpdb->term_relationships |
---|
77 | WHERE term_taxonomy_id $operator ( |
---|
78 | SELECT term_taxonomy_id |
---|
79 | FROM $wpdb->term_taxonomy |
---|
80 | WHERE taxonomy = %s |
---|
81 | AND term_id IN ($term_ids) |
---|
82 | ) |
---|
83 | )", $taxonomy); |
---|
84 | } |
---|
85 | |
---|
86 | // Example |
---|
87 | $query = wp_tax_and( |
---|
88 | wp_tax_or( |
---|
89 | wp_tax( 'post_category', 59 ), |
---|
90 | wp_tax( 'post_tag', 'web' ) |
---|
91 | ), |
---|
92 | wp_tax_not( 'post_category', 24 ), |
---|
93 | wp_tax_not( 'post_tag', 'wordpress' ) |
---|
94 | ); |
---|
95 | |
---|
96 | var_dump($query->get_sql()); |
---|
97 | |
---|