Taxonomy.php
2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php
namespace ACP\Sorting\Strategy;
use ACP;
use ACP\Sorting\AbstractModel;
use ACP\Sorting\Strategy;
use ACP\TermQueryInformation;
use WP_Term_Query;
class Taxonomy extends Strategy {
/**
* @var WP_Term_Query
*/
private $term_query;
/**
* @var string
*/
private $taxonomy;
public function __construct( AbstractModel $model, $taxonomy ) {
parent::__construct( $model );
$this->taxonomy = $taxonomy;
}
public function manage_sorting() {
add_action( 'pre_get_terms', [ $this, 'handle_sorting_request' ] );
}
/**
* @param array $args
*
* @return array
*/
public function get_results( array $args = [] ) {
return $this->get_terms( $args );
}
/**
* @param array $args
*
* @return int[]
*/
protected function get_terms( array $args = [] ) {
$defaults = [
'fields' => 'ids',
'taxonomy' => $this->taxonomy,
'hide_empty' => false,
];
$args = array_merge( $defaults, $args );
$query = new WP_Term_Query( $args );
return (array) $query->get_terms();
}
/**
* @return string
*/
public function get_order() {
return $this->get_query_var( 'order' );
}
/**
* @param WP_Term_Query $term_query
*/
private function set_term_query( WP_Term_Query $term_query ) {
$this->term_query = $term_query;
}
/**
* return boolean
*/
private function is_main_query() {
$term_query = new TermQueryInformation();
if ( ! $this->get_query_var( 'orderby' ) || ! $term_query->is_main_query( $this->term_query ) ) {
return false;
}
$taxonomies = $this->get_query_var( 'taxonomy' );
return ! ( empty( $taxonomies ) || ! in_array( $this->taxonomy, $taxonomies ) );
}
/**
* @param WP_Term_Query $query
*
* @return void
*/
public function handle_sorting_request( WP_Term_Query $query ) {
$this->set_term_query( $query );
if ( ! $this->is_main_query() ) {
return;
}
foreach ( $this->model->get_sorting_vars() as $key => $value ) {
if ( $this->is_universal_id( $key ) ) {
$key = 'include';
}
$query->query_vars[ $key ] = $value;
}
// pre-sorting done with an array
$include = $query->query_vars['include'];
if ( ! empty( $include ) ) {
$query->query_vars['orderby'] = 'include';
}
}
/**
* @return string
*/
public function get_taxonomy() {
$taxonomy = $this->get_query_var( 'taxonomy' );
return (string) $taxonomy[0];
}
/**
* @param string $var
*
* @return string|array|null
*/
protected function get_query_var( $var ) {
return $this->term_query instanceof WP_Term_Query && isset( $this->term_query->query_vars[ $var ] )
? $this->term_query->query_vars[ $var ]
: null;
}
}